Compare commits

...
Author SHA1 Message Date
lucioandClaude Fable 5 a9da249760 Remove unsafe-inline from script-src CSP
Move every inline <script> block and on*= attribute out of the templates
into per-page files under static/js/, then tighten the CSP to
script-src 'self' so injected inline scripts are actually blocked.

- static/js/base.js: QR modal, form[data-confirm] submit confirmation,
  and a shared glimmerCopy clipboard helper (loaded by base.html)
- One script per template: index, bin_view, bin_token, admin,
  admin_edit, admin_bin, admin_bin_edit, admin_uploads
- Template data now flows through data-* attributes (data-slug,
  data-filename, data-max-mb, ...) instead of being interpolated
  into JS; confirm() prompts use data-confirm
- style-src keeps unsafe-inline for the style="" attributes
- Update CLAUDE.md / AGENTS.md with the no-inline-JS rule

Verified in a live browser session: shorten flow, login, QR modal,
paste editor (token radios, name preview), paste cards (preview
dialog, expand/close), public paste view, token prompt redirect, and
uploads page - no console errors or CSP violations.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-06-09 20:14:30 -07:00
lucioandClaude Fable 5 82fb5122f3 Harden image decoding, shutdown, and CSRF cookie; add handler tests
- Reject images over 24 MP before full decode (decodeImageBounded) so a
  small PNG declaring huge dimensions cannot OOM the RPi Zero via the
  public thumbnail route or the resize handler
- Graceful shutdown on SIGINT/SIGTERM with a 10s drain so the SQLite DB
  closes cleanly on deploys
- Set the Secure flag on the csrf cookie (same isHTTPS rule as the
  session cookie); csrfToken is now a *Server method
- Add handlers_test.go: auth, login, CSRF, upload serving (traversal +
  forced attachment), and decompression-bomb coverage
- Track remaining work (CSP unsafe-inline removal) in plan.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-06-09 19:57:40 -07:00
lucioandClaude Fable 5 962f5d9e06 Fix security issues found in review
- Verify CSRF on POST /admin/uploads/resize (was the only state-changing
  admin route without a check) and cap its body at 1 MB
- limitBody: exact-match /admin/upload and /admin/upload-file instead of
  a prefix match that also exempted /admin/uploads/{delete,resize}
- Only honour X-Forwarded-Proto behind a trusted proxy (same rule as
  X-Forwarded-For); fall back to the configured base_url scheme for the
  session cookie Secure flag and baseURL()
- handleAdminBinSave: return 500 on non-ErrNoRows DB error instead of
  dereferencing a nil paste

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-06-09 19:43:32 -07:00
lucio cc26953d5e Add POST /api/links REST endpoint for short-link creation
Programmatic short-link creation that shares the same bearer key as the
MCP endpoint. Registered only when [mcp].enabled is true and api_key is
set, so a misconfigured server never exposes the route unauthenticated;
unauthenticated visitors hitting /api/links get a plain 404.

- POST /api/links accepts {"url","slug?"}, returns 201/200 with the
  same snake_case payload shape as the MCP create_link tool.
- Constant-time Bearer / X-API-Key auth (reuses mcpAPIKeyAuth helper).
- 4 KB body cap, DisallowUnknownFields, URL auto-scheme, dedupe on URL.
- 13 unit tests cover auth, validation, dedupe, and duplicate-slug.
2026-06-08 21:17:39 -07:00
lucio 9e10bc3031 Redesign UI to match Solis design system
Replace Pico CSS with a custom Solis-style design system — warm amber
on cream, Outfit font, 260px sidebar (logged in) or sticky public
header (logged out), soft amber-tinted shadows, cubic-bezier spring
animations on toasts and modals.

- Add static/css/style.css with the full design token system
- Add base.html + content-block pattern; each page defines its own
  {{define "content"}} and base.html provides the chrome
- pageData gains ActiveNav; adminPage(w, r, nav) sets it; handlers
  pass the right value for every admin route
- Standalone pages (login, 404, embed) render without base.html
- Templates use Solis-style data-table, card, stats-bar, tag-pill,
  alert, btn components
- Remove vendored Pico CSS (83KB) and the old style.css (12KB)
- Update AGENTS.md and CLAUDE.md to reflect the new design system

Bug fixes during the redesign:
- Preview dialog now only shows when [open] (UA default was being
  overridden by display:flex)
- Preview dialog centered via explicit top/left/transform — the
  browser's default margin:auto centering fights with display:flex
  on <dialog>
- Add ?embed=1 route that renders paste content without base.html
  chrome, so the admin paste preview iframe shows only the body

Tested: go build ./... clean, go vet ./... clean, binary boots.
2026-06-06 14:15:19 -07:00
lucioandClaude Opus 4.8 67731cfcac Persist sessions in SQLite so logins survive a server restart
Sessions were stored in an in-memory map, so every server reboot logged the
admin out. Back the session store with the database instead:

- Add a sessions table (token, expires_at, created_at) created via the existing
  migrate() (CREATE TABLE IF NOT EXISTS), backwards-compatible with deployed DBs.
- Add CreateSession / SessionValid / DeleteSession / CleanupSessions; expiry is
  checked in SQL against datetime('now') (UTC).
- sessionStore is now a thin DB-backed wrapper with the same Create/Valid/Delete
  interface; the hourly cleanup goroutine purges expired rows (plus once at
  startup). Login, logout, requireAuth, and isLoggedIn are unchanged.

The session cookie was already persistent (MaxAge), so logins now survive both
browser and server restarts until session_hours expiry.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-06-05 01:08:25 -07:00
lucio f1f535e722 Merge pull request #5 from luciochen233/fix-large-upload-413
Merge pull request #3 from luciochen233/paste-cards-redesign
2026-06-05 00:34:21 -07:00
lucio 9bebeb7f41 Merge pull request #4 from luciochen233/paste-cards-redesign
Merge paste-cards redesign into main
2026-06-05 00:29:23 -07:00
lucio e7089b4893 Merge pull request #2 from luciochen233/fix-large-upload-413
Fix large image uploads (bogus CSRF 403) + client-side compress-to-fit
2026-06-04 23:32:42 -07:00
lucio e030095987 Merge pull request #1 from luciochen233/fix-large-upload-413
Fix large image uploads failing with bogus CSRF 403 + add client-side…
2026-06-04 23:08:21 -07:00
36 changed files with 4089 additions and 1741 deletions

No files matched your search

+26 -13
View File
@@ -44,14 +44,21 @@ glimmer/
├── middleware.go # Auth, CSRF, sessions, rate limiter
├── templates.go # embed.FS for templates + static; initTemplates()
├── static/
│ ├── style.css # Custom styles on top of Pico CSS 2
│ ├── css/
│ │ └── style.css # Custom Solis-style design system (amber/cream, Outfit font)
│ ├── favicon.ico
│ ├── favicon.png
│ ├── js/ # Per-page scripts (CSP blocks inline JS)
│ │ ├── base.js # QR modal, data-confirm forms, glimmerCopy
│ │ └── *.js # One file per template that needs behaviour
│ └── upload.js # Shared client-side upload helper (window.GlimmerUpload)
└── templates/
├── base.html # Layout wrapper: sidebar (logged in) or public header
├── index.html # Public: URL shortener form
├── admin_login.html # Login (dark, centered)
├── admin_login.html # Login (light, centered card)
├── admin.html # Dashboard: stats, tiles, links tables
├── admin_edit.html # Edit a single link
├── admin_bin.html # Pastes list
├── admin_bin.html # Pastes list (cards + preview dialog)
├── admin_bin_edit.html # Create / edit paste (uses /static/upload.js)
├── admin_uploads.html # Image + file upload management
├── bin_view.html # Public paste viewer
@@ -85,11 +92,19 @@ All templates receive a `pageData` struct. Add new fields there when templates n
### Templates are embedded, not on disk
Templates and static files are embedded into the binary via `//go:embed` in `templates.go`. Changes to templates are compiled in; they are **not** reloaded at runtime. Always rebuild after template changes.
### No JS frameworks
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.
### No JS frameworks — and no inline JS
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). No build step, no npm, no bundler.
The CSP is `script-src 'self'`, so **inline `<script>` blocks and `on*=` attributes in templates are blocked by the browser**. All behaviour lives in files under `static/js/` (one per template, plus `base.js` for shared chrome: the QR modal, `glimmerCopy`, and `form[data-confirm]` submit confirmation). To pass template data to JS, put it in `data-*` attributes and read it from the script — never interpolate `{{...}}` into JS. Shared upload logic lives in `static/upload.js` as `window.GlimmerUpload`.
### CSS framework
[Pico CSS 2](https://picocss.com/) loaded from CDN. Custom overrides in `static/style.css`. Admin pages use `data-theme="dark"`.
**No CSS framework.** Glimmer uses a custom design system in `static/css/style.css` inspired by Solis's "Sunlight & Clarity" theme — warm amber (`#d97706`) on cream (`#fafaf9`) with Outfit font, sidebar + main-area layout, soft shadows with amber tint, cubic-bezier spring animations on toasts/modals. All templates are self-contained and offline-capable. **No external CDN dependencies.**
### Layout
Admin pages share a `base.html` layout that renders a 260px fixed sidebar (when `.LoggedIn`) or a sticky public header (otherwise). Each page template defines its own `{{define "content"}}...{{end}}` block; `base.html` calls `{{template "content" .}}` to inject it. The active sidebar item is driven by the `ActiveNav` field in `pageData` (`"links"`, `"pastes"`, `"uploads"`, or `"shorten"`). Use `s.adminPage(w, r, "links")` to get a pre-populated `pageData` for an admin route.
### Theme
Single light theme only — no `data-theme` switching. The design system is documented in the `:root` of `static/css/style.css`.
---
@@ -125,14 +140,12 @@ Shared upload rules:
Only PNG (`.png`) and JPEG (`.jpg`) are resizable. Resize uses a nearest-neighbour scale implemented in stdlib (`image`, `image/color`, `image/jpeg`, `image/png`) — no external image library. GIF and WebP are served and deletable but not resizable.
### Admin tabs
Every admin page (`admin.html`, `admin_bin.html`, `admin_bin_edit.html`, `admin_uploads.html`) must include the full three-tab nav. Add the `active` class to the correct tab:
```html
<div class="admin-tabs">
<a href="/admin" class="tab-link [active]">Links</a>
<a href="/admin/bin" class="tab-link [active]">Pastes</a>
<a href="/admin/uploads" class="tab-link [active]">Uploads</a>
</div>
Admin pages share a sidebar rendered by `base.html`. To highlight the current section, set `ActiveNav` on the `pageData`:
```go
d := s.adminPage(w, r, "pastes") // highlights the Pastes nav item
renderTemplate(w, "admin_bin.html", d)
```
Valid values are `"links"`, `"pastes"`, `"uploads"`, `"shorten"`. New admin pages should follow the same `base.html` + `{{define "content"}}` pattern and live under `templates/`.
### Database migrations
Migrations run automatically in `db.Open()`. New columns are added with `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`. Never drop columns — the schema must remain backwards compatible with existing `data/urls.db` files on deployed instances.
+26 -13
View File
@@ -44,14 +44,21 @@ glimmer/
├── middleware.go # Auth, CSRF, sessions, rate limiter
├── templates.go # embed.FS for templates + static; initTemplates()
├── static/
│ ├── style.css # Custom styles on top of Pico CSS 2
│ ├── css/
│ │ └── style.css # Custom Solis-style design system (amber/cream, Outfit font)
│ ├── favicon.ico
│ ├── favicon.png
│ ├── js/ # Per-page scripts (CSP blocks inline JS)
│ │ ├── base.js # QR modal, data-confirm forms, glimmerCopy
│ │ └── *.js # One file per template that needs behaviour
│ └── upload.js # Shared client-side upload helper (window.GlimmerUpload)
└── templates/
├── base.html # Layout wrapper: sidebar (logged in) or public header
├── index.html # Public: URL shortener form
├── admin_login.html # Login (dark, centered)
├── admin_login.html # Login (light, centered card)
├── admin.html # Dashboard: stats, tiles, links tables
├── admin_edit.html # Edit a single link
├── admin_bin.html # Pastes list
├── admin_bin.html # Pastes list (cards + preview dialog)
├── admin_bin_edit.html # Create / edit paste (uses /static/upload.js)
├── admin_uploads.html # Image + file upload management
├── bin_view.html # Public paste viewer
@@ -85,11 +92,19 @@ All templates receive a `pageData` struct. Add new fields there when templates n
### Templates are embedded, not on disk
Templates and static files are embedded into the binary via `//go:embed` in `templates.go`. Changes to templates are compiled in; they are **not** reloaded at runtime. Always rebuild after template changes.
### No JS frameworks
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.
### No JS frameworks — and no inline JS
All JavaScript is vanilla ES5-style (`var`, not `const`/`let`). No build step, no npm, no bundler.
The CSP is `script-src 'self'`, so **inline `<script>` blocks and `on*=` attributes in templates are blocked by the browser**. All behaviour lives in files under `static/js/` (one per template, plus `base.js` for shared chrome: the QR modal, `glimmerCopy`, and `form[data-confirm]` submit confirmation). To pass template data to JS, put it in `data-*` attributes and read it from the script — never interpolate `{{...}}` into JS. Shared upload logic lives in `static/upload.js` as `window.GlimmerUpload`.
### CSS framework
[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`).
**No CSS framework.** Glimmer uses a custom design system in `static/css/style.css` inspired by Solis's "Sunlight & Clarity" theme — warm amber (`#d97706`) on cream (`#fafaf9`) with Outfit font, sidebar + main-area layout, soft shadows with amber tint, cubic-bezier spring animations on toasts/modals. The CSS is served from `/static/css/style.css` so the app works fully offline. The Outfit font itself is loaded from Google Fonts (one external request); replace with a vendored woff2 if you need a true air-gapped build. Do not reintroduce CDN `<link>`/`<script>`/image references — everything must be same-origin (enforced by the `Content-Security-Policy` header in `securityHeaders`).
### Layout
Admin pages share a `base.html` layout that renders a 260px fixed sidebar (when `.LoggedIn`) or a sticky public header (otherwise). Each page template defines its own `{{define "content"}}...{{end}}` block; `base.html` calls `{{template "content" .}}` to inject it. The active sidebar item is driven by the `ActiveNav` field in `pageData` (`"links"`, `"pastes"`, `"uploads"`, or `"shorten"`). Use `s.adminPage(w, r, "links")` to get a pre-populated `pageData` for an admin route.
### Theme
Single light theme only — no `data-theme` switching. The design tokens are documented in the `:root` of `static/css/style.css`.
---
@@ -125,14 +140,12 @@ Shared upload rules:
Only PNG (`.png`) and JPEG (`.jpg`) are resizable. Resize uses a nearest-neighbour scale implemented in stdlib (`image`, `image/color`, `image/jpeg`, `image/png`) — no external image library. GIF and WebP are served and deletable but not resizable.
### Admin tabs
Every admin page (`admin.html`, `admin_bin.html`, `admin_bin_edit.html`, `admin_uploads.html`) must include the full three-tab nav. Add the `active` class to the correct tab:
```html
<div class="admin-tabs">
<a href="/admin" class="tab-link [active]">Links</a>
<a href="/admin/bin" class="tab-link [active]">Pastes</a>
<a href="/admin/uploads" class="tab-link [active]">Uploads</a>
</div>
Admin pages share a sidebar rendered by `base.html`. To highlight the current section, set `ActiveNav` on the `pageData`:
```go
d := s.adminPage(w, r, "pastes") // highlights the Pastes nav item
renderTemplate(w, "admin_bin.html", d)
```
Valid values are `"links"`, `"pastes"`, `"uploads"`, `"shorten"`. New admin pages should follow the same `base.html` + `{{define "content"}}` pattern and live under `templates/`.
### Database migrations
Migrations run automatically in `db.Open()`. New columns are added with `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`. Never drop columns — the schema must remain backwards compatible with existing `data/urls.db` files on deployed instances.
+52
View File
@@ -188,6 +188,57 @@ api_key = "replace-with-a-long-random-token"
MCP clients can authenticate with `Authorization: Bearer <api_key>` or `X-API-Key: <api_key>`. Basic auth using the configured admin username and password is also accepted. The endpoint exposes tools for listing, creating, updating, and deleting links and pastes, plus listing and deleting upload metadata/files.
### REST API
A small REST surface shares the same `[mcp].api_key`. It is registered only when `[mcp].enabled = true` **and** `api_key` is set, so a misconfigured server never exposes the endpoint unauthenticated. The route is intentionally undocumented in any public-facing template — visitors who don't know it exists get a 404.
#### `POST /api/links`
Create a short link. Authenticate with `Authorization: Bearer <api_key>` or `X-API-Key: <api_key>`. Both are checked with constant-time comparison.
Request body (JSON):
```json
{
"url": "https://example.com/very/long/path",
"slug": "docs" // optional; omit for auto-generated
}
```
Rules:
- `url` — required. Max 2048 chars. Must be `http://` or `https://`. Bare domains are auto-prefixed with `https://`.
- `slug` — optional. Lowercase letters, digits, hyphens, and underscores, up to 64 chars.
- Deduplication: if the same URL is submitted twice and no custom slug is given, the second call returns the existing link with HTTP 200 (idempotent).
- Links created via the API are recorded as `created_by = "admin"` and appear in the admin dashboard.
Responses:
- `201 Created` — new link created. Body is the link payload.
- `200 OK` — same URL already existed; returns the existing link.
- `400 Bad Request` — invalid JSON, bad URL, or bad slug.
- `401 Unauthorized` — missing or wrong API key.
- `409 Conflict` — custom slug already taken.
- `500 Internal Server Error` — database error.
Response body (snake_case to match the MCP payload):
```json
{
"id": 42,
"slug": "docs",
"url": "https://example.com/very/long/path",
"short_url": "https://s.example.com/docs",
"created_by": "admin",
"clicks": 0,
"created_at": "2026-06-08T20:36:55Z"
}
```
Example:
```bash
curl -X POST https://s.example.com/api/links \
-H "Authorization: Bearer $GLIMMER_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url":"https://example.com/docs","slug":"docs"}'
```
### 4. Build and run
```bash
@@ -444,6 +495,7 @@ If proxying through Cloudflare, `X-Forwarded-For` is safe to trust for rate limi
| `POST` | `/admin/uploads/delete/{filename}` | Admin | Delete an uploaded file (CSRF) |
| `POST` | `/admin/uploads/resize/{filename}` | Admin | Resize a PNG/JPEG in-place (returns JSON) |
| `POST` | `/mcp` | MCP auth | JSON-RPC MCP endpoint, when `[mcp].enabled = true` |
| `POST` | `/api/links` | API key | REST: create a short link (when `[mcp].enabled = true` and `api_key` is set) |
| `GET` | `/static/*` | Public | CSS / static assets |
---
+40
View File
@@ -87,6 +87,12 @@ func migrate(conn *sql.DB) error {
original_name TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);
`)
if err != nil {
return fmt.Errorf("running migrations: %w", err)
@@ -288,6 +294,40 @@ func scanPaste(row *sql.Row) (*Paste, error) {
return &p, nil
}
// ---- Sessions (persisted so logins survive a server restart) ----
// CreateSession stores a session token with an absolute expiry. Times are
// stored in UTC to match SQLite's datetime('now'), which is also UTC.
func (d *DB) CreateSession(token string, expiresAt time.Time) error {
_, err := d.conn.Exec(
"INSERT OR REPLACE INTO sessions (token, expires_at) VALUES (?, ?)",
token, expiresAt.UTC().Format("2006-01-02 15:04:05"),
)
return err
}
// SessionValid reports whether a token exists and has not expired. The expiry
// comparison happens in SQL against datetime('now') (UTC).
func (d *DB) SessionValid(token string) (bool, error) {
var count int
err := d.conn.QueryRow(
"SELECT COUNT(*) FROM sessions WHERE token = ? AND expires_at > datetime('now')",
token,
).Scan(&count)
return count > 0, err
}
func (d *DB) DeleteSession(token string) error {
_, err := d.conn.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
}
// CleanupSessions removes expired sessions.
func (d *DB) CleanupSessions() error {
_, err := d.conn.Exec("DELETE FROM sessions WHERE expires_at <= datetime('now')")
return err
}
// ---- Upload metadata ----
func (d *DB) RecordUpload(filename, originalName string) error {
+168
View File
@@ -0,0 +1,168 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"strings"
"glimmer/internal/db"
"glimmer/internal/slug"
)
// apiKeyAuth checks the configured MCP API key via constant-time comparison.
// Reuses the same authentication scheme as POST /mcp so operators only need
// to provision one secret. The route is registered only when [mcp].enabled
// is true and an api_key is configured, but we still refuse empty keys as
// defence in depth.
func (s *Server) apiKeyAuth(r *http.Request) bool {
if s.cfg.MCP.APIKey == "" {
return false
}
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
}
func writeAPIError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if status == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", `Bearer realm="Glimmer API"`)
}
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
}
func writeAPIJSON(w http.ResponseWriter, status int, payload any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
}
// apiCreateLinkRequest is the body of POST /api/links.
type apiCreateLinkRequest struct {
URL string `json:"url"`
Slug string `json:"slug,omitempty"`
}
// apiLinkResponse is the REST view of a short link. Field names mirror the
// existing MCP payload (snake_case) so anyone already consuming mcpLink can
// reuse the same parsing code on the REST side.
type apiLinkResponse struct {
ID int64 `json:"id"`
Slug string `json:"slug"`
URL string `json:"url"`
ShortURL string `json:"short_url"`
CreatedBy string `json:"created_by"`
Clicks int64 `json:"clicks"`
CreatedAt string `json:"created_at,omitempty"`
}
func (s *Server) toAPILink(link db.Link) apiLinkResponse {
return apiLinkResponse{
ID: link.ID,
Slug: link.Slug,
URL: link.URL,
ShortURL: joinBaseURL(s.baseURLForAPI(), "/"+link.Slug),
CreatedBy: link.CreatedBy,
Clicks: link.Clicks,
CreatedAt: formatMCPTime(link.CreatedAt),
}
}
// baseURLForAPI returns the base URL used when building short URLs in API
// responses. The configured BaseURL is preferred; the request Host is taken
// into account by the public web UI but for a JSON API the operator should
// set BaseURL to their public hostname (e.g. https://s.example.com) so the
// short URL is clickable from the start.
func (s *Server) baseURLForAPI() string {
if s.cfg.Server.BaseURL != "" {
return s.cfg.Server.BaseURL
}
return "http://localhost"
}
// apiCreateLink is the REST equivalent of the MCP create_link tool. It
// accepts a JSON body, validates the URL, optionally honours a custom
// slug, deduplicates identical URLs, and returns the created link.
func (s *Server) apiCreateLink(w http.ResponseWriter, r *http.Request) {
if !s.apiKeyAuth(r) {
writeAPIError(w, http.StatusUnauthorized, "unauthorized")
return
}
// JSON bodies are tiny; 4 KB is plenty and stops a misbehaving client
// from streaming a large body just to push us against rate limits.
r.Body = http.MaxBytesReader(w, r.Body, 4096)
defer r.Body.Close()
var req apiCreateLinkRequest
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
writeAPIError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
return
}
rawURL := strings.TrimSpace(req.URL)
if err := validateRedirectURL(&rawURL); err != nil {
writeAPIError(w, http.StatusBadRequest, err.Error())
return
}
finalSlug := strings.ToLower(strings.TrimSpace(req.Slug))
if finalSlug != "" {
if err := validateAPISlug(finalSlug); err != nil {
writeAPIError(w, http.StatusBadRequest, err.Error())
return
}
exists, err := s.db.SlugExists(finalSlug)
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "database error")
return
}
if exists {
writeAPIError(w, http.StatusConflict, "slug already taken")
return
}
} else {
// Deduplicate identical URLs — matches the public web UI behaviour
// and keeps the link count down for API clients that retry.
if existing, err := s.db.GetByURL(rawURL); err == nil {
writeAPIJSON(w, http.StatusOK, s.toAPILink(*existing))
return
}
var err error
finalSlug, err = s.generateUniqueSlug()
if err != nil {
writeAPIError(w, http.StatusInternalServerError, err.Error())
return
}
}
link, err := s.db.Create(finalSlug, rawURL, "admin")
if err != nil {
writeAPIError(w, http.StatusInternalServerError, "failed to create link")
return
}
writeAPIJSON(w, http.StatusCreated, s.toAPILink(*link))
}
// validateAPISlug enforces the same character rules the admin web UI uses:
// letters, digits, hyphens, and underscores, 1–64 characters. Centralised
// so future rule changes only need one edit.
func validateAPISlug(value string) error {
if value == "" {
return errors.New("slug is required")
}
if len(value) > 64 {
return errors.New("slug is too long (max 64 characters)")
}
return slug.Validate(value)
}
+319
View File
@@ -0,0 +1,319 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"glimmer/internal/config"
"glimmer/internal/db"
)
func TestAPICreateLinkRequiresAuth(t *testing.T) {
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: "secret"},
})
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com"}`))
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
if !strings.Contains(rec.Header().Get("WWW-Authenticate"), "Bearer") {
t.Fatalf("expected WWW-Authenticate header, got %q", rec.Header().Get("WWW-Authenticate"))
}
}
func TestAPICreateLinkRejectsBadKey(t *testing.T) {
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: "secret"},
})
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com"}`))
req.Header.Set("Authorization", "Bearer wrong")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
}
func TestAPICreateLinkRejectsEmptyKeyConfig(t *testing.T) {
// Even if the route somehow got registered with no key configured,
// apiKeyAuth must refuse. This is the defence-in-depth check.
srv := newTestServer(&config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: ""},
})
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com"}`))
req.Header.Set("Authorization", "Bearer anything")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 when no key is configured, got %d", rec.Code)
}
}
func TestAPICreateLinkWithBearerKey(t *testing.T) {
srv := apiTestServer(t, "secret")
body := strings.NewReader(`{"url":"https://example.com/page"}`)
req := httptest.NewRequest(http.MethodPost, "/api/links", body)
req.Header.Set("Authorization", "Bearer secret")
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("expected 201, got %d body=%s", rec.Code, rec.Body.String())
}
var resp apiLinkResponse
if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
t.Fatalf("decode response: %v", err)
}
if resp.URL != "https://example.com/page" {
t.Fatalf("unexpected URL: %q", resp.URL)
}
if resp.ShortURL != "http://localhost:8888/"+resp.Slug {
t.Fatalf("unexpected short_url: %q", resp.ShortURL)
}
if resp.Slug == "" {
t.Fatalf("expected auto-generated slug, got empty")
}
if resp.CreatedBy != "admin" {
t.Fatalf("expected created_by=admin, got %q", resp.CreatedBy)
}
}
func TestAPICreateLinkWithXAPIKeyHeader(t *testing.T) {
srv := apiTestServer(t, "secret")
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com"}`))
req.Header.Set("X-API-Key", "secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("expected 201, got %d", rec.Code)
}
}
func TestAPICreateLinkWithCustomSlug(t *testing.T) {
srv := apiTestServer(t, "secret")
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com","slug":"docs"}`))
req.Header.Set("Authorization", "Bearer secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("expected 201, got %d body=%s", rec.Code, rec.Body.String())
}
var resp apiLinkResponse
_ = json.NewDecoder(rec.Body).Decode(&resp)
if resp.Slug != "docs" {
t.Fatalf("expected slug=docs, got %q", resp.Slug)
}
}
func TestAPICreateLinkRejectsBadURL(t *testing.T) {
srv := apiTestServer(t, "secret")
cases := []string{
`{"url":""}`,
`{"url":"not a url at all with spaces"}`,
`{"url":"javascript:alert(1)"}`,
`{"url":"ftp://example.com"}`,
`{"url":"//missing-scheme"}`,
}
for _, body := range cases {
t.Run(body, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for %s, got %d", body, rec.Code)
}
})
}
}
func TestAPICreateLinkAutoSchemesBareDomain(t *testing.T) {
srv := apiTestServer(t, "secret")
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"example.com/foo"}`))
req.Header.Set("Authorization", "Bearer secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("expected 201, got %d body=%s", rec.Code, rec.Body.String())
}
var resp apiLinkResponse
_ = json.NewDecoder(rec.Body).Decode(&resp)
if resp.URL != "https://example.com/foo" {
t.Fatalf("expected auto-scheme upgrade, got %q", resp.URL)
}
}
func TestAPICreateLinkRejectsBadSlug(t *testing.T) {
srv := apiTestServer(t, "secret")
cases := []string{
`{"url":"https://example.com","slug":"with space"}`,
`{"url":"https://example.com","slug":"with/slash"}`,
}
for _, body := range cases {
t.Run(body, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for %s, got %d", body, rec.Code)
}
})
}
}
func TestAPICreateLinkRejectsDuplicateSlug(t *testing.T) {
srv := apiTestServer(t, "secret")
first := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com/a","slug":"docs"}`))
first.Header.Set("Authorization", "Bearer secret")
rec1 := httptest.NewRecorder()
srv.apiCreateLink(rec1, first)
if rec1.Code != http.StatusCreated {
t.Fatalf("first create: expected 201, got %d", rec1.Code)
}
second := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com/b","slug":"docs"}`))
second.Header.Set("Authorization", "Bearer secret")
rec2 := httptest.NewRecorder()
srv.apiCreateLink(rec2, second)
if rec2.Code != http.StatusConflict {
t.Fatalf("duplicate slug: expected 409, got %d body=%s", rec2.Code, rec2.Body.String())
}
}
func TestAPICreateLinkDeduplicatesURL(t *testing.T) {
srv := apiTestServer(t, "secret")
body := `{"url":"https://example.com/dedupe"}`
// First call: 201 Created with a fresh slug.
req1 := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body))
req1.Header.Set("Authorization", "Bearer secret")
rec1 := httptest.NewRecorder()
srv.apiCreateLink(rec1, req1)
if rec1.Code != http.StatusCreated {
t.Fatalf("first call: expected 201, got %d body=%s", rec1.Code, rec1.Body.String())
}
var first apiLinkResponse
_ = json.NewDecoder(rec1.Body).Decode(&first)
// Second call: same URL, 200 OK with the existing link (idempotent).
req2 := httptest.NewRequest(http.MethodPost, "/api/links", strings.NewReader(body))
req2.Header.Set("Authorization", "Bearer secret")
rec2 := httptest.NewRecorder()
srv.apiCreateLink(rec2, req2)
if rec2.Code != http.StatusOK {
t.Fatalf("second call: expected 200, got %d body=%s", rec2.Code, rec2.Body.String())
}
var second apiLinkResponse
_ = json.NewDecoder(rec2.Body).Decode(&second)
if first.ID != second.ID || first.Slug != second.Slug {
t.Fatalf("dedupe mismatch: first=%+v second=%+v", first, second)
}
// And exactly one row was inserted.
links, err := srv.db.List()
if err != nil {
t.Fatalf("list: %v", err)
}
count := 0
for _, l := range links {
if l.URL == "https://example.com/dedupe" {
count++
}
}
if count != 1 {
t.Fatalf("expected exactly 1 link for the URL, got %d", count)
}
}
func TestAPICreateLinkRejectsMalformedJSON(t *testing.T) {
srv := apiTestServer(t, "secret")
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url": this is not json}`))
req.Header.Set("Authorization", "Bearer secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", rec.Code)
}
}
func TestAPICreateLinkRejectsUnknownFields(t *testing.T) {
srv := apiTestServer(t, "secret")
req := httptest.NewRequest(http.MethodPost, "/api/links",
strings.NewReader(`{"url":"https://example.com","unexpected":"field"}`))
req.Header.Set("Authorization", "Bearer secret")
rec := httptest.NewRecorder()
srv.apiCreateLink(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for unknown field, got %d", rec.Code)
}
}
// apiTestServer builds a Server wired up with a real on-disk SQLite DB so
// the full happy-path can be exercised. Reuses newTestServer for the auth
// fields; only adds a db handle.
func apiTestServer(t *testing.T, apiKey string) *Server {
t.Helper()
database, err := db.Open(filepath.Join(t.TempDir(), "urls.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { _ = database.Close() })
return &Server{
cfg: &config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
MCP: config.MCPConfig{Enabled: true, APIKey: apiKey},
Slugs: config.SlugConfig{Length: 3},
},
db: database,
authLimiter: newRateLimiter(0),
bcryptSem: make(chan struct{}, 1),
}
}
+93 -32
View File
@@ -53,6 +53,7 @@ type pageData struct {
PasteBody template.HTML
Uploads any
LoggedIn bool
ActiveNav string // "links" | "pastes" | "uploads" | "shorten" — for sidebar highlight
CSRFToken string
UploadMaxMB int64
}
@@ -124,15 +125,27 @@ func (s *Server) baseURL(r *http.Request) string {
if host == "" {
return s.cfg.Server.BaseURL
}
proto := r.Header.Get("X-Forwarded-Proto")
if proto == "" {
proto = "http"
// X-Forwarded-Proto is client-settable, so it is only honoured behind a
// trusted proxy (same rule as X-Forwarded-For). Otherwise fall back to
// the configured base URL's scheme.
proto := "http"
if s.isHTTPS(r) {
proto = "https"
}
return proto + "://" + host
}
// isHTTPS reports whether the request should be treated as HTTPS: either the
// trusted proxy says so, or the operator configured an https base URL.
func (s *Server) isHTTPS(r *http.Request) bool {
if s.cfg.Server.TrustProxy && r.Header.Get("X-Forwarded-Proto") == "https" {
return true
}
return strings.HasPrefix(s.cfg.Server.BaseURL, "https://")
}
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)})
renderTemplate(w, "index.html", pageData{BaseURL: s.baseURL(r), LoggedIn: s.isLoggedIn(r), CSRFToken: s.csrfToken(w, r)})
}
func (s *Server) handleShorten(w http.ResponseWriter, r *http.Request) {
@@ -243,7 +256,7 @@ func (s *Server) renderIndex(w http.ResponseWriter, r *http.Request, errMsg, sho
OriginalURL: originalURL,
QRSVG: qrsvg,
LoggedIn: s.isLoggedIn(r),
CSRFToken: csrfToken(w, r),
CSRFToken: s.csrfToken(w, r),
})
}
@@ -278,14 +291,14 @@ func (s *Server) handleRedirect(w http.ResponseWriter, r *http.Request) {
// 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)})
renderTemplate(w, "admin_login.html", pageData{BaseURL: s.baseURL(r), CSRFToken: s.csrfToken(w, r)})
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
// 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)})
renderTemplate(w, "admin_login.html", pageData{Error: "Too many attempts. Please wait a moment.", CSRFToken: s.csrfToken(w, r)})
return
}
@@ -300,12 +313,12 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
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)})
renderTemplate(w, "admin_login.html", pageData{Error: "Server busy. Please try again.", CSRFToken: s.csrfToken(w, r)})
return
}
if !userOK || !pwOK {
w.WriteHeader(http.StatusUnauthorized)
renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: csrfToken(w, r)})
renderTemplate(w, "admin_login.html", pageData{Error: "Invalid credentials", CSRFToken: s.csrfToken(w, r)})
return
}
@@ -315,7 +328,7 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
return
}
secure := r.Header.Get("X-Forwarded-Proto") == "https"
secure := s.isHTTPS(r)
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: token,
@@ -344,11 +357,12 @@ func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (s *Server) adminPage(w http.ResponseWriter, r *http.Request) pageData {
func (s *Server) adminPage(w http.ResponseWriter, r *http.Request, nav string) pageData {
return pageData{
BaseURL: s.baseURL(r),
LoggedIn: true,
CSRFToken: csrfToken(w, r),
ActiveNav: nav,
CSRFToken: s.csrfToken(w, r),
UploadMaxMB: s.cfg.Upload.MaxSize,
}
}
@@ -367,7 +381,7 @@ func (s *Server) handleAdmin(w http.ResponseWriter, r *http.Request) {
topLinks, _ := s.db.TopLinks("admin", 20)
d := s.adminPage(w, r)
d := s.adminPage(w, r, "links")
d.AdminLinks = adminLinks
d.AnonLinks = anonLinks
d.TopLinks = topLinks
@@ -391,7 +405,7 @@ func (s *Server) handleAdminEdit(w http.ResponseWriter, r *http.Request) {
return
}
d := s.adminPage(w, r)
d := s.adminPage(w, r, "links")
d.Link = link
renderTemplate(w, "admin_edit.html", d)
}
@@ -408,7 +422,7 @@ func (s *Server) handleAdminEditSave(w http.ResponseWriter, r *http.Request) {
renderEditErr := func(msg string) {
link, _ := s.db.GetByID(id)
d := s.adminPage(w, r)
d := s.adminPage(w, r, "links")
d.Link = link
d.Error = msg
renderTemplate(w, "admin_edit.html", d)
@@ -531,6 +545,17 @@ func (s *Server) handleBinView(w http.ResponseWriter, r *http.Request) {
body = template.HTML("<pre><code>" + template.HTMLEscapeString(paste.Content) + "</code></pre>")
}
// Embed view — used by admin paste preview iframe; strips the page chrome
// (sidebar / public header / toolbar / card wrapper) so only the paste body renders.
if r.URL.Query().Get("embed") == "1" {
renderTemplate(w, "bin_view_embed.html", pageData{
BaseURL: s.baseURL(r),
Paste: paste,
PasteBody: body,
})
return
}
renderTemplate(w, "bin_view.html", pageData{
BaseURL: s.baseURL(r),
Paste: paste,
@@ -553,13 +578,13 @@ func (s *Server) handleAdminBin(w http.ResponseWriter, r *http.Request) {
ThumbURL: thumbURLFor(firstPasteImage(p.Content)),
})
}
d := s.adminPage(w, r)
d := s.adminPage(w, r, "pastes")
d.Pastes = cards
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))
renderTemplate(w, "admin_bin_edit.html", s.adminPage(w, r, "pastes"))
}
func (s *Server) handleAdminBinCreate(w http.ResponseWriter, r *http.Request) {
@@ -574,7 +599,7 @@ func (s *Server) handleAdminBinCreate(w http.ResponseWriter, r *http.Request) {
hidden := r.FormValue("hidden") == "1"
newErrPage := func(msg string) {
d := s.adminPage(w, r)
d := s.adminPage(w, r, "pastes")
d.Error = msg
renderTemplate(w, "admin_bin_edit.html", d)
}
@@ -635,7 +660,7 @@ func (s *Server) handleAdminBinEdit(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
d := s.adminPage(w, r)
d := s.adminPage(w, r, "pastes")
d.Paste = paste
renderTemplate(w, "admin_bin_edit.html", d)
}
@@ -651,6 +676,10 @@ func (s *Server) handleAdminBinSave(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
name := strings.TrimSpace(r.FormValue("name"))
title := strings.TrimSpace(r.FormValue("title"))
@@ -663,7 +692,7 @@ func (s *Server) handleAdminBinSave(w http.ResponseWriter, r *http.Request) {
hidden := r.FormValue("hidden") == "1"
editErrPage := func(msg string) {
d := s.adminPage(w, r)
d := s.adminPage(w, r, "pastes")
d.Paste = paste
d.Error = msg
renderTemplate(w, "admin_bin_edit.html", d)
@@ -785,6 +814,36 @@ func scaleImage(src image.Image, maxDim int) image.Image {
return dst
}
// maxDecodePixels caps the pixel count of images we are willing to fully
// decode. A small compressed file can declare enormous dimensions (a
// decompression bomb): 24 MP decodes to ~96 MB of NRGBA, which is already a
// big bite on an RPi Zero — anything larger is rejected before decode.
const maxDecodePixels = 24 << 20
// decodeImageBounded decodes an image file, but reads only the header first
// and refuses files whose decoded size would exceed maxDecodePixels. The
// dimension product uses int64 so a malicious header cannot overflow 32-bit
// int on ARMv5.
func decodeImageBounded(path string) (image.Image, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
cfg, _, err := image.DecodeConfig(f)
if err != nil {
return nil, err
}
if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > maxDecodePixels {
return nil, fmt.Errorf("image dimensions too large (%dx%d, max %d megapixels)", cfg.Width, cfg.Height, maxDecodePixels>>20)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
src, _, err := image.Decode(f)
return src, err
}
// ---- Thumbnails ----
const thumbMaxDim = 512 // long-side size of generated thumbnails, in pixels
@@ -809,12 +868,7 @@ func (s *Server) generateThumbnail(filename string) error {
if !isImageFile(filename) {
return fmt.Errorf("not an image")
}
f, err := os.Open(filepath.Join(s.cfg.Upload.Dir, filename))
if err != nil {
return err
}
src, _, err := image.Decode(f)
f.Close()
src, err := decodeImageBounded(filepath.Join(s.cfg.Upload.Dir, filename))
if err != nil {
return err
}
@@ -1035,7 +1089,7 @@ func (s *Server) handleAdminUploads(w http.ResponseWriter, r *http.Request) {
return uploads[i].ModTime.After(uploads[j].ModTime)
})
d := s.adminPage(w, r)
d := s.adminPage(w, r, "uploads")
d.Uploads = uploads
renderTemplate(w, "admin_uploads.html", d)
}
@@ -1053,6 +1107,15 @@ func (s *Server) handleAdminUploadDelete(w http.ResponseWriter, r *http.Request)
}
func (s *Server) handleAdminUploadResize(w http.ResponseWriter, r *http.Request) {
// The resize request arrives as multipart FormData, so CSRF is verified
// here rather than via the requireCSRF wrapper (see CLAUDE.md). The body
// is tiny — cap it before the form parse triggered by verifyCSRF.
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
if !verifyCSRF(r) {
jsonError(w, "Invalid CSRF token", http.StatusForbidden)
return
}
filename := r.PathValue("filename")
if !validUploadFilename(filename) {
jsonError(w, "Invalid filename", http.StatusBadRequest)
@@ -1070,15 +1133,13 @@ func (s *Server) handleAdminUploadResize(w http.ResponseWriter, r *http.Request)
}
path := filepath.Join(s.cfg.Upload.Dir, filename)
f, err := os.Open(path)
if err != nil {
if _, err := os.Stat(path); err != nil {
jsonError(w, "File not found", http.StatusNotFound)
return
}
src, _, err := image.Decode(f)
f.Close()
src, err := decodeImageBounded(path)
if err != nil {
jsonError(w, "Failed to decode image", http.StatusInternalServerError)
jsonError(w, "Failed to decode image: "+err.Error(), http.StatusUnprocessableEntity)
return
}
+367
View File
@@ -0,0 +1,367 @@
package server
import (
"bytes"
"encoding/binary"
"hash/crc32"
"image"
"image/png"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
"glimmer/internal/config"
"glimmer/internal/db"
"golang.org/x/crypto/bcrypt"
)
// webTestServer builds a Server wired like production (DB, sessions, upload
// dir, templates) for exercising the web handlers. mutate can adjust the
// config before the server is built.
func webTestServer(t *testing.T, mutate func(*config.Config)) *Server {
t.Helper()
initTemplates()
database, err := db.Open(filepath.Join(t.TempDir(), "urls.db"))
if err != nil {
t.Fatalf("open db: %v", err)
}
t.Cleanup(func() { _ = database.Close() })
cfg := &config.Config{
Server: config.ServerConfig{BaseURL: "http://localhost:8888"},
Admin: config.AdminConfig{Username: "admin", SessionHours: 1},
Slugs: config.SlugConfig{Length: 3},
Upload: config.UploadConfig{Dir: t.TempDir(), MaxSize: 50},
}
if mutate != nil {
mutate(cfg)
}
return &Server{
cfg: cfg,
db: database,
sessions: newSessionStore(database, time.Hour),
limiter: newRateLimiter(0),
authLimiter: newRateLimiter(0),
bcryptSem: make(chan struct{}, 1),
}
}
func sessionCookie(t *testing.T, s *Server) *http.Cookie {
t.Helper()
token, err := s.sessions.Create()
if err != nil {
t.Fatalf("create session: %v", err)
}
return &http.Cookie{Name: "session", Value: token}
}
// ---- Auth ----
func TestRequireAuthRedirectsAnonymous(t *testing.T) {
s := webTestServer(t, nil)
handler := s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("handler must not run without a session")
})
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusSeeOther {
t.Fatalf("expected 303, got %d", rec.Code)
}
if loc := rec.Header().Get("Location"); loc != "/admin/login" {
t.Fatalf("expected redirect to /admin/login, got %q", loc)
}
}
func TestRequireAuthAcceptsValidSession(t *testing.T) {
s := webTestServer(t, nil)
called := false
handler := s.requireAuth(func(w http.ResponseWriter, r *http.Request) { called = true })
req := httptest.NewRequest(http.MethodGet, "/admin", nil)
req.AddCookie(sessionCookie(t, s))
handler(httptest.NewRecorder(), req)
if !called {
t.Fatal("handler should run with a valid session")
}
}
func TestLoginWrongPasswordRejected(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("correct-horse"), bcrypt.MinCost)
if err != nil {
t.Fatalf("bcrypt: %v", err)
}
s := webTestServer(t, func(cfg *config.Config) {
cfg.Admin.PasswordHash = string(hash)
})
form := url.Values{"username": {"admin"}, "password": {"wrong"}}
req := httptest.NewRequest(http.MethodPost, "/admin/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
s.handleLogin(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", rec.Code)
}
for _, c := range rec.Result().Cookies() {
if c.Name == "session" {
t.Fatal("no session cookie may be set on failed login")
}
}
}
func TestLoginSuccessSetsSessionCookie(t *testing.T) {
hash, err := bcrypt.GenerateFromPassword([]byte("correct-horse"), bcrypt.MinCost)
if err != nil {
t.Fatalf("bcrypt: %v", err)
}
s := webTestServer(t, func(cfg *config.Config) {
cfg.Admin.PasswordHash = string(hash)
})
form := url.Values{"username": {"admin"}, "password": {"correct-horse"}}
req := httptest.NewRequest(http.MethodPost, "/admin/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
s.handleLogin(rec, req)
if rec.Code != http.StatusSeeOther {
t.Fatalf("expected 303, got %d body=%s", rec.Code, rec.Body.String())
}
var session *http.Cookie
for _, c := range rec.Result().Cookies() {
if c.Name == "session" {
session = c
}
}
if session == nil || session.Value == "" {
t.Fatal("expected a session cookie on successful login")
}
if !session.HttpOnly {
t.Fatal("session cookie must be HttpOnly")
}
if !s.sessions.Valid(session.Value) {
t.Fatal("issued session token should validate")
}
}
// ---- CSRF ----
func TestRequireCSRFRejectsMissingToken(t *testing.T) {
s := webTestServer(t, nil)
handler := s.requireCSRF(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("handler must not run without a CSRF token")
})
req := httptest.NewRequest(http.MethodPost, "/admin/delete/1", nil)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", rec.Code)
}
}
func TestRequireCSRFAcceptsMatchingToken(t *testing.T) {
s := webTestServer(t, nil)
called := false
handler := s.requireCSRF(func(w http.ResponseWriter, r *http.Request) { called = true })
token := strings.Repeat("a", 64)
form := url.Values{"csrf_token": {token}}
req := httptest.NewRequest(http.MethodPost, "/admin/delete/1", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(&http.Cookie{Name: "csrf", Value: token})
handler(httptest.NewRecorder(), req)
if !called {
t.Fatal("handler should run with matching CSRF cookie and form token")
}
}
func TestResizeRejectsMissingCSRF(t *testing.T) {
s := webTestServer(t, nil)
req := httptest.NewRequest(http.MethodPost, "/admin/uploads/resize/x", strings.NewReader("max_dim=512"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetPathValue("filename", strings.Repeat("a", 32)+".png")
rec := httptest.NewRecorder()
s.handleAdminUploadResize(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("expected 403 without CSRF token, got %d", rec.Code)
}
}
func TestCSRFCookieSecureFollowsBaseURL(t *testing.T) {
s := webTestServer(t, func(cfg *config.Config) {
cfg.Server.BaseURL = "https://luci.ooo"
})
rec := httptest.NewRecorder()
s.csrfToken(rec, httptest.NewRequest(http.MethodGet, "/", nil))
var csrf *http.Cookie
for _, c := range rec.Result().Cookies() {
if c.Name == "csrf" {
csrf = c
}
}
if csrf == nil {
t.Fatal("expected a csrf cookie to be set")
}
if !csrf.Secure {
t.Fatal("csrf cookie must be Secure when base_url is https")
}
}
// ---- Upload serving ----
func writeUploadFile(t *testing.T, s *Server, name string, content []byte) {
t.Helper()
if err := os.WriteFile(filepath.Join(s.cfg.Upload.Dir, name), content, 0644); err != nil {
t.Fatalf("write upload: %v", err)
}
}
func TestUploadsServeRejectsInvalidNames(t *testing.T) {
s := webTestServer(t, nil)
for _, name := range []string{
"../config.toml",
"..%2f..%2fconfig.toml",
"notahash.txt",
strings.Repeat("a", 32), // no extension
strings.Repeat("a", 32) + ".html/extra",
} {
req := httptest.NewRequest(http.MethodGet, "/uploads/"+name, nil)
rec := httptest.NewRecorder()
s.handleUploadsServe(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("name %q: expected 404, got %d", name, rec.Code)
}
}
}
func TestUploadsServeForcesAttachmentForNonImages(t *testing.T) {
s := webTestServer(t, nil)
name := strings.Repeat("ab", 16) + ".html"
writeUploadFile(t, s, name, []byte("<script>alert(1)</script>"))
req := httptest.NewRequest(http.MethodGet, "/uploads/"+name, nil)
rec := httptest.NewRecorder()
s.handleUploadsServe(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/octet-stream" {
t.Fatalf("expected octet-stream, got %q", ct)
}
if cd := rec.Header().Get("Content-Disposition"); !strings.HasPrefix(cd, "attachment") {
t.Fatalf("expected attachment disposition, got %q", cd)
}
}
func TestUploadsServeImagesInline(t *testing.T) {
s := webTestServer(t, nil)
name := strings.Repeat("cd", 16) + ".png"
writeUploadFile(t, s, name, smallPNG(t))
req := httptest.NewRequest(http.MethodGet, "/uploads/"+name, nil)
rec := httptest.NewRecorder()
s.handleUploadsServe(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", rec.Code)
}
if cd := rec.Header().Get("Content-Disposition"); cd != "" {
t.Fatalf("images should be served inline, got disposition %q", cd)
}
}
// ---- Decompression-bomb guard ----
func smallPNG(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
if err := png.Encode(&buf, image.NewNRGBA(image.Rect(0, 0, 10, 10))); err != nil {
t.Fatalf("encode png: %v", err)
}
return buf.Bytes()
}
// bombPNGHeader builds a syntactically valid PNG signature + IHDR chunk that
// declares the given dimensions. DecodeConfig succeeds on it; a full decode
// of real data at this size would allocate width*height*4 bytes.
func bombPNGHeader(width, height uint32) []byte {
var buf bytes.Buffer
buf.Write([]byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a})
ihdr := make([]byte, 13)
binary.BigEndian.PutUint32(ihdr[0:4], width)
binary.BigEndian.PutUint32(ihdr[4:8], height)
ihdr[8] = 8 // bit depth
ihdr[9] = 6 // color type RGBA
chunk := append([]byte("IHDR"), ihdr...)
binary.Write(&buf, binary.BigEndian, uint32(13))
buf.Write(chunk)
binary.Write(&buf, binary.BigEndian, crc32.ChecksumIEEE(chunk))
return buf.Bytes()
}
func TestDecodeImageBoundedRejectsHugeDimensions(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "bomb.png")
// 50000x50000 = 2.5 gigapixels — would decode to ~10 GB of NRGBA.
if err := os.WriteFile(path, bombPNGHeader(50000, 50000), 0644); err != nil {
t.Fatalf("write bomb: %v", err)
}
if _, err := decodeImageBounded(path); err == nil {
t.Fatal("expected oversized image to be rejected before decode")
} else if !strings.Contains(err.Error(), "too large") {
t.Fatalf("expected dimension error, got: %v", err)
}
}
func TestDecodeImageBoundedAcceptsNormalImage(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "ok.png")
if err := os.WriteFile(path, smallPNG(t), 0644); err != nil {
t.Fatalf("write png: %v", err)
}
img, err := decodeImageBounded(path)
if err != nil {
t.Fatalf("expected small image to decode, got: %v", err)
}
if b := img.Bounds(); b.Dx() != 10 || b.Dy() != 10 {
t.Fatalf("unexpected bounds: %v", b)
}
}
func TestThumbRouteRefusesBombViaFallback(t *testing.T) {
// A bomb header upload must not OOM the public thumb route: generation
// fails the bounds check and the handler falls back to serving the
// original bytes without decoding them.
s := webTestServer(t, nil)
name := strings.Repeat("ef", 16) + ".png"
writeUploadFile(t, s, name, bombPNGHeader(50000, 50000))
req := httptest.NewRequest(http.MethodGet, "/uploads/thumb/"+name, nil)
req.SetPathValue("filename", name)
rec := httptest.NewRecorder()
s.handleThumb(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200 fallback, got %d", rec.Code)
}
if _, err := os.Stat(s.thumbPath(name)); !os.IsNotExist(err) {
t.Fatal("no thumbnail may be generated for an oversized image")
}
}
+21 -37
View File
@@ -10,20 +10,21 @@ import (
"sync"
"time"
"glimmer/internal/db"
"golang.org/x/crypto/bcrypt"
)
// sessionStore persists sessions in the database so logins survive a server
// restart. It is a thin wrapper around the DB with a periodic cleanup of
// expired rows.
type sessionStore struct {
mu sync.RWMutex
sessions map[string]time.Time
ttl time.Duration
db *db.DB
ttl time.Duration
}
func newSessionStore(ttl time.Duration) *sessionStore {
s := &sessionStore{
sessions: make(map[string]time.Time),
ttl: ttl,
}
func newSessionStore(database *db.DB, ttl time.Duration) *sessionStore {
s := &sessionStore{db: database, ttl: ttl}
database.CleanupSessions() // purge anything already expired at startup
go s.cleanup()
return s
}
@@ -32,14 +33,7 @@ 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()
s.db.CleanupSessions()
}
}
@@ -49,32 +43,19 @@ func (s *sessionStore) Create() (string, error) {
return "", err
}
token := hex.EncodeToString(b)
s.mu.Lock()
s.sessions[token] = time.Now().Add(s.ttl)
s.mu.Unlock()
if err := s.db.CreateSession(token, time.Now().Add(s.ttl)); err != nil {
return "", err
}
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
ok, _ := s.db.SessionValid(token)
return ok
}
func (s *sessionStore) Delete(token string) {
s.mu.Lock()
delete(s.sessions, token)
s.mu.Unlock()
s.db.DeleteSession(token)
}
func (srv *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
@@ -92,7 +73,7 @@ func (srv *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
// 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 {
func (srv *Server) csrfToken(w http.ResponseWriter, r *http.Request) string {
if c, err := r.Cookie("csrf"); err == nil && len(c.Value) == 64 {
return c.Value
}
@@ -104,6 +85,7 @@ func csrfToken(w http.ResponseWriter, r *http.Request) string {
Value: token,
Path: "/",
SameSite: http.SameSiteLaxMode,
Secure: srv.isHTTPS(r),
MaxAge: 86400,
})
return token
@@ -223,7 +205,9 @@ func limitConcurrency(max int, next http.Handler) http.Handler {
// 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") {
// Exact-match the two upload endpoints: a prefix match would also
// exempt /admin/uploads/* (delete, resize) from the body cap.
if r.Method == http.MethodPost && r.URL.Path != "/admin/upload" && r.URL.Path != "/admin/upload-file" {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
next.ServeHTTP(w, r)
+46 -9
View File
@@ -1,13 +1,17 @@
package server
import (
"context"
"errors"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"time"
"glimmer/internal/config"
@@ -34,7 +38,7 @@ func New(cfg *config.Config, database *db.DB) *Server {
return &Server{
cfg: cfg,
db: database,
sessions: newSessionStore(ttl),
sessions: newSessionStore(database, ttl),
limiter: newRateLimiter(1 * time.Second),
authLimiter: newRateLimiter(1 * time.Second),
bcryptSem: make(chan struct{}, bcryptWorkers),
@@ -48,19 +52,23 @@ func securityHeaders(next http.Handler) http.Handler {
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
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
// All assets are served from the same origin (CSS and JS are embedded),
// 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, and blob: so the client-side image compressor
// (canvas) can load a selected file before upload. 'unsafe-inline' is required by the inline
// scripts/styles in the templates; object-src/base-uri are pinned to
// blunt injection; frame-ancestors 'self' permits the same-origin paste
// (canvas) can load a selected file before upload. script-src is
// 'self' only — all JS lives in /static/js/ files; do not add inline
// <script> blocks or on*= attributes to templates, they will be
// blocked. style-src keeps 'unsafe-inline' for the style="" attributes
// throughout the templates (style injection is far lower risk than
// script injection). object-src/base-uri are pinned to blunt
// injection; frame-ancestors 'self' permits the same-origin paste
// preview iframe while blocking cross-site clickjacking.
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"img-src 'self' data: https: blob:; "+
"style-src 'self' 'unsafe-inline'; "+
"script-src 'self' 'unsafe-inline'; "+
"script-src 'self'; "+
"object-src 'none'; "+
"base-uri 'none'; "+
"frame-ancestors 'self'")
@@ -135,6 +143,14 @@ func (s *Server) Start() error {
if s.cfg.MCP.Enabled {
mux.HandleFunc("POST /mcp", s.handleMCP)
// REST surface for programmatic short-link creation. Shares the
// same API key as /mcp. Only registered when the API key is set so
// a misconfigured server never exposes the endpoint unauthenticated.
// The route is intentionally not documented in any public-facing
// template; visitors who don't know it exists get a 404.
if s.cfg.MCP.APIKey != "" {
mux.HandleFunc("POST /api/links", s.apiCreateLink)
}
}
// Pastebin public routes (before catch-all)
@@ -167,5 +183,26 @@ func (s *Server) Start() error {
}
log.Printf("Starting server on %s (base URL: %s)", addr, s.cfg.Server.BaseURL)
return srv.ListenAndServe()
// Graceful shutdown: on SIGINT/SIGTERM stop accepting connections, let
// in-flight requests drain (bounded), then return so deferred cleanup
// (e.g. closing the SQLite DB) runs instead of being killed mid-write.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
errCh := make(chan error, 1)
go func() { errCh <- srv.ListenAndServe() }()
select {
case err := <-errCh:
return err
case <-ctx.Done():
log.Printf("Shutting down...")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil && !errors.Is(err, context.DeadlineExceeded) {
return err
}
return nil
}
}
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
// Admin dashboard: hostname compression for tiles and QR modal buttons.
(function() {
'use strict';
// Compress URL displays to hostname for visual cleanliness
document.querySelectorAll('[data-hostname]').forEach(function(el) {
try {
var u = new URL(el.textContent.trim());
el.textContent = u.hostname + (u.pathname !== '/' ? u.pathname : '');
} catch (e) {}
});
document.querySelectorAll('.js-qr').forEach(function(btn) {
btn.addEventListener('click', function() {
var slug = btn.getAttribute('data-slug');
window.openQRModal(slug, slug);
});
});
})();
+99
View File
@@ -0,0 +1,99 @@
// Admin pastes grid: preview dialog, copy-link, QR, and card click handling.
(function() {
'use strict';
function previewURL(name, token) {
var u = '/bin/' + encodeURIComponent(name);
if (token) u += '/' + encodeURIComponent(token);
return u;
}
function openPreview(name, token, title) {
var dlg = document.getElementById('preview-dialog');
var fullURL = previewURL(name, token);
// iframe uses the embed view so it strips the sidebar / header / toolbar —
// only the paste body is rendered inside the dialog.
var embedURL = fullURL + '?embed=1';
document.getElementById('preview-frame').src = embedURL;
// The "Open ↗" link goes to the full URL (with chrome) so a new tab shows the
// normal public page.
document.getElementById('preview-open').href = fullURL;
document.getElementById('preview-title').textContent = title || name;
dlg.classList.remove('expanded');
document.getElementById('preview-expand').innerHTML = '⤢';
document.getElementById('preview-expand').setAttribute('aria-label', 'Expand');
dlg.showModal();
}
function closePreview() {
document.getElementById('preview-dialog').close();
}
function toggleExpand() {
var dlg = document.getElementById('preview-dialog');
var expanded = dlg.classList.toggle('expanded');
var btn = document.getElementById('preview-expand');
btn.innerHTML = expanded ? '⤡' : '⤢';
btn.setAttribute('aria-label', expanded ? 'Shrink' : 'Expand');
}
function showBinQR(name, full) {
var url = location.origin + '/bin/' + encodeURIComponent(name);
var fetchUrl = '/admin/bin/qr/' + encodeURIComponent(name);
if (full) fetchUrl += '?full=1';
var overlay = document.getElementById('qr-modal-overlay');
document.getElementById('qr-modal-image').src = fetchUrl;
document.getElementById('qr-modal-link').textContent = url + (full ? ' (with token)' : '');
var dl = document.getElementById('qr-modal-download');
dl.href = fetchUrl;
dl.download = name + '_QR.svg';
overlay.classList.add('show');
}
// Per-card wiring: action buttons read name/token/title from the card's
// data attributes; clicking the card itself (not an action) opens the
// preview. Clicks on links/buttons/forms are ignored by the card handler,
// so the action buttons need no stopPropagation.
document.querySelectorAll('.js-preview').forEach(function(el) {
var copyBtn = el.querySelector('.js-copy-link');
if (copyBtn) {
copyBtn.addEventListener('click', function() {
var url = location.origin + previewURL(el.dataset.name, el.dataset.token);
window.glimmerCopy(url, copyBtn);
});
}
var qrBtn = el.querySelector('.js-bin-qr');
if (qrBtn) {
qrBtn.addEventListener('click', function() {
showBinQR(el.dataset.name, false);
});
}
el.addEventListener('click', function(e) {
if (e.target.closest('.paste-card-actions')) return;
if (e.target.closest('a, button, form, input')) return;
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
});
el.setAttribute('tabindex', '0');
el.setAttribute('role', 'button');
el.addEventListener('keydown', function(e) {
if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('.paste-card-actions')) {
e.preventDefault();
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
}
});
});
var expandBtn = document.getElementById('preview-expand');
if (expandBtn) expandBtn.addEventListener('click', toggleExpand);
var closeBtn = document.getElementById('preview-close');
if (closeBtn) closeBtn.addEventListener('click', closePreview);
// Clear iframe when dialog closes
var dlg = document.getElementById('preview-dialog');
if (dlg) {
dlg.addEventListener('close', function() {
document.getElementById('preview-frame').src = 'about:blank';
});
}
})();
@@ -0,0 +1,65 @@
// Paste editor: token radio toggling, name preview, and upload wiring.
(function() {
'use strict';
function toggleCustomToken() {
var wrap = document.getElementById('custom-token-wrap');
if (!wrap) return;
var checked = document.querySelector('input[name="token_action"][value="custom"]:checked') ||
document.querySelector('input[name="enable_token"][value="custom"]:checked');
wrap.style.display = checked ? 'block' : 'none';
}
document.querySelectorAll('input[name="token_action"], input[name="enable_token"]').forEach(function(radio) {
radio.addEventListener('change', toggleCustomToken);
});
toggleCustomToken();
// Slug preview updater
var nameInput = document.getElementById('name');
var preview = document.getElementById('name-preview');
if (nameInput && preview) {
nameInput.addEventListener('input', function() {
preview.textContent = this.value || '...';
});
}
var textarea = document.querySelector('textarea[name="content"]');
var status = document.getElementById('upload-status');
var imgBtn = document.getElementById('upload-img-btn');
function insertAtCursor(text) {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = textarea.value.substring(0, start);
var after = textarea.value.substring(end);
textarea.value = before + text + '\n' + after;
textarea.selectionStart = textarea.selectionEnd = start + text.length + 1;
textarea.focus();
}
var uploader = window.GlimmerUpload.init({
imgBtn: imgBtn,
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: status,
maxImageMB: parseInt(imgBtn.getAttribute('data-max-mb'), 10) || 50,
onUploaded: function(data) {
insertAtCursor(data.markdown);
status.textContent = 'Uploaded';
setTimeout(function() { status.textContent = ''; }, 3000);
}
});
textarea.addEventListener('paste', function(e) {
var items = (e.clipboardData || {}).items || [];
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
e.preventDefault();
uploader.doUpload(items[i].getAsFile(), true);
return;
}
}
});
})();
+12
View File
@@ -0,0 +1,12 @@
// Edit-link page: live slug preview.
(function() {
'use strict';
var slugInput = document.getElementById('slug');
var preview = document.getElementById('slug-preview');
if (slugInput && preview) {
slugInput.addEventListener('input', function() {
preview.textContent = this.value || '...';
});
}
})();
@@ -0,0 +1,77 @@
// Uploads admin page: copy-markdown, resize dialog, and upload wiring.
(function() {
'use strict';
var currentResizeFile = '';
document.querySelectorAll('.js-copy-md').forEach(function(btn) {
btn.addEventListener('click', function() {
var filename = btn.getAttribute('data-filename');
var url = '/uploads/' + filename;
var label = btn.getAttribute('data-original') || filename;
var md = btn.getAttribute('data-image') ? '![](' + url + ')' : '[' + label + '](' + url + ')';
window.glimmerCopy(md, btn);
});
});
document.querySelectorAll('.js-resize').forEach(function(btn) {
btn.addEventListener('click', function() {
currentResizeFile = btn.getAttribute('data-filename');
document.getElementById('resize-current').textContent =
'Current: ' + btn.getAttribute('data-width') + '×' + btn.getAttribute('data-height');
document.getElementById('resize-status').textContent = '';
document.getElementById('resize-confirm').disabled = false;
document.getElementById('resize-dialog').showModal();
});
});
document.querySelectorAll('.js-resize-cancel').forEach(function(btn) {
btn.addEventListener('click', function() {
document.getElementById('resize-dialog').close();
});
});
document.getElementById('resize-confirm').addEventListener('click', function() {
var dim = document.getElementById('resize-dim').value;
var status = document.getElementById('resize-status');
var btn = this;
status.textContent = 'Resizing…';
btn.disabled = true;
var fd = new FormData();
fd.append('csrf_token', window.GlimmerUpload.getCsrfToken());
fd.append('max_dim', dim);
fetch('/admin/uploads/resize/' + currentResizeFile, { method: 'POST', body: fd, credentials: 'same-origin' })
.then(function(r) { return r.json(); })
.then(function(data) {
btn.disabled = false;
if (data.error) {
status.textContent = 'Error: ' + data.error;
return;
}
var sizeEl = document.getElementById('size-' + currentResizeFile);
var dimEl = document.getElementById('dim-' + currentResizeFile);
if (sizeEl) sizeEl.textContent = data.size_human;
if (dimEl) dimEl.textContent = data.width + '×' + data.height;
status.textContent = 'Done — ' + data.size_human;
var imgs = document.querySelectorAll('img[src="/uploads/' + currentResizeFile + '"]');
imgs.forEach(function(img) { img.src = '/uploads/' + currentResizeFile + '?t=' + Date.now(); });
})
.catch(function() {
btn.disabled = false;
status.textContent = 'Failed';
});
});
var imgBtn = document.getElementById('upload-img-btn');
window.GlimmerUpload.init({
imgBtn: imgBtn,
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: document.getElementById('upload-status'),
maxImageMB: parseInt(imgBtn.getAttribute('data-max-mb'), 10) || 50,
onUploaded: function() { location.reload(); }
});
})();
+56
View File
@@ -0,0 +1,56 @@
// Shared chrome behaviour for every layout page: QR modal, confirm-on-submit
// forms, and a clipboard helper. The CSP blocks inline scripts, so all page
// behaviour lives in files under /static/js/.
(function() {
'use strict';
// Copy text to the clipboard and flash the button label. Used by the
// per-page scripts.
window.glimmerCopy = function(text, btn) {
var orig = btn.textContent;
navigator.clipboard.writeText(text).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
};
window.openQRModal = function(slug, name) {
var overlay = document.getElementById('qr-modal-overlay');
document.getElementById('qr-modal-image').src = '/admin/qr/' + slug;
document.getElementById('qr-modal-link').textContent = '/admin/qr/' + slug;
var dl = document.getElementById('qr-modal-download');
dl.href = '/admin/qr/' + slug;
dl.download = (name || slug) + '_QR.svg';
overlay.classList.add('show');
};
window.closeQRModal = function() {
document.getElementById('qr-modal-overlay').classList.remove('show');
document.getElementById('qr-modal-image').src = '';
};
var overlay = document.getElementById('qr-modal-overlay');
if (overlay) {
overlay.addEventListener('click', function(e) {
if (e.target === overlay) window.closeQRModal();
});
}
var closeBtn = document.getElementById('qr-modal-close');
if (closeBtn) {
closeBtn.addEventListener('click', function() { window.closeQRModal(); });
}
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') window.closeQRModal();
});
// Forms with data-confirm ask before submitting (replaces inline
// onsubmit="return confirm(...)"). Delegated so it works for any form.
document.addEventListener('submit', function(e) {
var form = e.target;
if (form && form.getAttribute && form.getAttribute('data-confirm')) {
if (!window.confirm(form.getAttribute('data-confirm'))) {
e.preventDefault();
}
}
});
})();
+15
View File
@@ -0,0 +1,15 @@
// Token prompt for protected pastes: redirect to /bin/{name}/{token}.
(function() {
'use strict';
var form = document.getElementById('token-form');
if (form) {
form.addEventListener('submit', function(e) {
e.preventDefault();
var token = document.getElementById('token-input').value.trim();
if (token) {
window.location.href = window.location.pathname + '/' + encodeURIComponent(token);
}
});
}
})();
+11
View File
@@ -0,0 +1,11 @@
// Public paste viewer: copy-raw-content button.
(function() {
'use strict';
var btn = document.getElementById('copy-paste-btn');
if (btn) {
btn.addEventListener('click', function() {
window.glimmerCopy(document.getElementById('paste-raw').innerText, btn);
});
}
})();
+21
View File
@@ -0,0 +1,21 @@
// Public URL shortener page.
(function() {
'use strict';
var form = document.getElementById('shorten-form');
if (form) {
form.addEventListener('submit', function() {
var input = document.getElementById('url');
if (input.value && input.value.indexOf('://') === -1) {
input.value = 'https://' + input.value;
}
});
}
var copyBtn = document.getElementById('copy-short-url');
if (copyBtn) {
copyBtn.addEventListener('click', function() {
window.glimmerCopy(document.getElementById('short-url').textContent, copyBtn);
});
}
})();
-4
View File
@@ -1,4 +0,0 @@
@charset "UTF-8";/*!
* Pico CSS ✨ v2.1.1 (https://picocss.com)
* Copyright 2019-2025 - Licensed under MIT
*/:host,:root{--pico-font-family-emoji:"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--pico-font-family-sans-serif:system-ui,"Segoe UI",Roboto,Oxygen,Ubuntu,Cantarell,Helvetica,Arial,"Helvetica Neue",sans-serif,var(--pico-font-family-emoji);--pico-font-family-monospace:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace,var(--pico-font-family-emoji);--pico-font-family:var(--pico-font-family-sans-serif);--pico-line-height:1.5;--pico-font-weight:400;--pico-font-size:100%;--pico-text-underline-offset:0.1rem;--pico-border-radius:0.25rem;--pico-border-width:0.0625rem;--pico-outline-width:0.125rem;--pico-transition:0.2s ease-in-out;--pico-spacing:1rem;--pico-typography-spacing-vertical:1rem;--pico-block-spacing-vertical:var(--pico-spacing);--pico-block-spacing-horizontal:var(--pico-spacing);--pico-grid-column-gap:var(--pico-spacing);--pico-grid-row-gap:var(--pico-spacing);--pico-form-element-spacing-vertical:0.75rem;--pico-form-element-spacing-horizontal:1rem;--pico-group-box-shadow:0 0 0 rgba(0, 0, 0, 0);--pico-group-box-shadow-focus-with-button:0 0 0 var(--pico-outline-width) var(--pico-primary-focus);--pico-group-box-shadow-focus-with-input:0 0 0 0.0625rem var(--pico-form-element-border-color);--pico-modal-overlay-backdrop-filter:blur(0.375rem);--pico-nav-element-spacing-vertical:1rem;--pico-nav-element-spacing-horizontal:0.5rem;--pico-nav-link-spacing-vertical:0.5rem;--pico-nav-link-spacing-horizontal:0.5rem;--pico-nav-breadcrumb-divider:">";--pico-icon-checkbox:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-minus:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(255, 255, 255)' stroke-width='4' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='5' y1='12' x2='19' y2='12'%3E%3C/line%3E%3C/svg%3E");--pico-icon-chevron:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-date:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='3' y='4' width='18' height='18' rx='2' ry='2'%3E%3C/rect%3E%3Cline x1='16' y1='2' x2='16' y2='6'%3E%3C/line%3E%3Cline x1='8' y1='2' x2='8' y2='6'%3E%3C/line%3E%3Cline x1='3' y1='10' x2='21' y2='10'%3E%3C/line%3E%3C/svg%3E");--pico-icon-time:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='10'%3E%3C/circle%3E%3Cpolyline points='12 6 12 12 16 14'%3E%3C/polyline%3E%3C/svg%3E");--pico-icon-search:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'%3E%3C/circle%3E%3Cline x1='21' y1='21' x2='16.65' y2='16.65'%3E%3C/line%3E%3C/svg%3E");--pico-icon-close:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none' stroke='rgb(136, 145, 164)' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cline x1='18' y1='6' x2='6' y2='18'%3E%3C/line%3E%3Cline x1='6' y1='6' x2='18' y2='18'%3E%3C/line%3E%3C/svg%3E");--pico-icon-loading:url("data:image/svg+xml,%3Csvg fill='none' height='24' width='24' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg' %3E%3Cstyle%3E g %7B animation: rotate 2s linear infinite; transform-origin: center center; %7D circle %7B stroke-dasharray: 75,100; stroke-dashoffset: -5; animation: dash 1.5s ease-in-out infinite; stroke-linecap: round; %7D @keyframes rotate %7B 0%25 %7B transform: rotate(0deg); %7D 100%25 %7B transform: rotate(360deg); %7D %7D @keyframes dash %7B 0%25 %7B stroke-dasharray: 1,100; stroke-dashoffset: 0; %7D 50%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -17.5; %7D 100%25 %7B stroke-dasharray: 44.5,100; stroke-dashoffset: -62; %7D %7D %3C/style%3E%3Cg%3E%3Ccircle cx='12' cy='12' r='10' fill='none' stroke='rgb(136, 145, 164)' stroke-width='4' /%3E%3C/g%3E%3C/svg%3E")}@media (min-width:576px){:host,:root{--pico-font-size:106.25%}}@media (min-width:768px){:host,:root{--pico-font-size:112.5%}}@media (min-width:1024px){:host,:root{--pico-font-size:118.75%}}@media (min-width:1280px){:host,:root{--picLine truncated
-644
View File
@@ -1,644 +0,0 @@
: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"] a[role="button"],
[role="group"] form button,
[role="group"] button {
padding: 0.25rem 0.5rem;
font-size: 0.85rem;
margin: 0;
white-space: nowrap;
}
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);
}
mark.badge-hidden {
background: color-mix(in srgb, var(--pico-del-color) 15%, transparent);
color: var(--pico-del-color);
border: 1px solid var(--pico-del-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;
}
/* Image upload controls */
.upload-controls {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 0.25rem;
}
.upload-controls button {
width: auto;
margin: 0;
padding: 0.3rem 0.75rem;
font-size: 0.85rem;
}
#upload-status {
color: var(--pico-muted-color);
font-size: 0.8rem;
}
.ext-chip {
display: inline-block;
font-family: var(--pico-font-family-monospace);
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
padding: 0.1rem 0.4rem;
border-radius: 4px;
background: var(--pico-primary-background);
color: var(--pico-primary-inverse);
min-width: 2.5rem;
text-align: center;
}
/* ── Pastes masonry cards (Xiaohongshu style) ───────────────────────── */
.pcard-grid {
columns: 240px;
column-gap: 1rem;
margin-top: 1rem;
}
.pcard {
break-inside: avoid;
display: inline-block;
width: 100%;
margin: 0 0 1rem;
padding: 0;
background: var(--pico-card-background-color);
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
overflow: hidden;
cursor: pointer;
transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s;
}
.pcard:hover {
transform: translateY(-2px);
}
.pcard:focus-visible {
outline: 2px solid var(--pico-primary);
outline-offset: 2px;
}
.pcard:hover .pcard-img {
opacity: 0.92;
}
.pcard:hover {
border-color: var(--pico-primary);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}
.pcard-imgwrap {
display: block;
width: 100%;
margin: 0;
padding: 0;
border: 0;
background: none;
cursor: pointer;
line-height: 0;
}
.pcard-img {
width: 100%;
height: auto;
display: block;
transition: opacity 0.15s;
}
.pcard-imgwrap:hover .pcard-img {
opacity: 0.9;
}
.pcard-body {
padding: 0.75rem;
}
.pcard-title {
display: block;
width: 100%;
margin: 0 0 0.35rem;
padding: 0;
border: 0;
background: none;
text-align: left;
font-weight: 600;
font-size: 1rem;
line-height: 1.3;
color: var(--pico-color);
cursor: pointer;
}
.pcard-title:hover {
color: var(--pico-primary);
}
.pcard-summary {
margin: 0 0 0.5rem;
font-size: 0.85rem;
line-height: 1.45;
color: var(--pico-muted-color);
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.pcard-meta {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.3rem;
margin-bottom: 0.6rem;
font-size: 0.72rem;
color: var(--pico-muted-color);
}
.pcard-date {
margin-left: auto;
font-variant-numeric: tabular-nums;
}
.pcard-actions {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
cursor: default;
}
.pcard-actions form {
margin: 0;
display: flex;
}
.pcard-actions a[role="button"],
.pcard-actions button {
margin: 0;
padding: 0.2rem 0.5rem;
font-size: 0.78rem;
white-space: nowrap;
}
/* ── In-page paste preview modal ────────────────────────────────────── */
.preview-dialog {
width: min(820px, 94vw);
height: min(80vh, 920px);
max-width: none;
max-height: none;
padding: 0;
border: 1px solid var(--pico-muted-border-color);
border-radius: 16px;
background: var(--pico-card-background-color);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.55);
overflow: hidden;
transition: width 0.22s ease, height 0.22s ease;
}
/* dialog is only laid out when open; scope flex so closed state stays hidden */
.preview-dialog[open] {
display: flex;
flex-direction: column;
}
/* Expanded fills the main content area, not the whole viewport. */
.preview-dialog.expanded {
width: min(1180px, 94vw);
height: 88vh;
}
.preview-dialog::backdrop {
background: rgba(0, 0, 0, 0.55);
backdrop-filter: blur(3px);
}
.preview-head {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.55rem 0.6rem 0.55rem 1rem;
background: var(--pico-card-background-color);
border-bottom: 1px solid var(--pico-muted-border-color);
}
.preview-title {
flex: 1;
min-width: 0;
font-weight: 600;
font-size: 0.95rem;
color: var(--pico-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.preview-actions {
flex: 0 0 auto;
display: flex;
gap: 0.4rem;
align-items: center;
}
.preview-actions a,
.preview-actions button {
margin: 0;
border-radius: 8px;
}
/* square icon buttons for expand / close */
#preview-expand,
.preview-close {
width: 2rem;
padding: 0.25rem 0;
text-align: center;
line-height: 1;
font-size: 0.95rem;
}
.preview-close {
background: transparent;
border: 1px solid var(--pico-muted-border-color);
color: var(--pico-muted-color);
}
.preview-close:hover {
background: var(--pico-del-color);
border-color: var(--pico-del-color);
color: #fff;
}
.preview-frame {
flex: 1 1 auto;
width: 100%;
border: 0;
background: var(--pico-background-color);
}
+51 -3
View File
@@ -2,6 +2,7 @@ package server
import (
"embed"
"fmt"
"html/template"
"io"
)
@@ -12,12 +13,59 @@ var templateFS embed.FS
//go:embed all:static
var staticFS embed.FS
var templates *template.Template
var templateMap map[string]*template.Template
func initTemplates() {
templates = template.Must(template.ParseFS(templateFS, "templates/*.html"))
templateMap = make(map[string]*template.Template)
// Pages that use the base layout (sidebar if logged in, public header otherwise).
// Each gets its own parsed template set so their {{define "content"}} blocks don't collide.
layoutPages := []string{
"index.html",
"admin.html",
"admin_edit.html",
"admin_bin.html",
"admin_bin_edit.html",
"admin_uploads.html",
"bin_view.html",
"bin_token.html",
}
for _, page := range layoutPages {
t := template.Must(
template.New("").ParseFS(templateFS, "templates/base.html", "templates/"+page),
)
templateMap[page] = t
}
// Standalone pages (no base layout wrapper) — render themselves directly.
standalonePages := []string{
"admin_login.html",
"404.html",
"bin_view_embed.html", // for ?embed=1 iframe preview
}
for _, page := range standalonePages {
t := template.Must(
template.New("").ParseFS(templateFS, "templates/"+page),
)
templateMap[page] = t
}
}
func renderTemplate(w io.Writer, name string, data any) error {
return templates.ExecuteTemplate(w, name, data)
t, ok := templateMap[name]
if !ok {
return fmt.Errorf("template %q not found", name)
}
// Layout pages render via the base template (which calls {{template "content" .}}).
// Standalone pages render by their own filename.
standalone := map[string]bool{
"admin_login.html": true,
"404.html": true,
"bin_view_embed.html": true,
}
if standalone[name] {
return t.ExecuteTemplate(w, name, data)
}
return t.ExecuteTemplate(w, "base", data)
}
+27 -16
View File
@@ -1,23 +1,34 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Not Found — Glimmer</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
<title>Not Found — Glimmer</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</a></strong></li></ul>
<ul><li><a href="/">Home</a></li></ul>
</nav>
<main class="container" style="text-align:center;padding-top:6rem;max-width:640px">
<p style="font-size:8rem;line-height:1;margin:0;font-weight:800;opacity:0.15">404</p>
<h2 style="margin-top:0.5rem">Page Not Found</h2>
<p style="color:var(--pico-muted-color)">The page you're looking for doesn't exist or may have been removed.</p>
<a href="/" role="button" style="margin-top:1.5rem">Go Home</a>
</main>
<div class="app-container public-layout">
<header class="public-header">
<a href="/" class="public-brand">
<div class="brand-logo">G</div>
<span class="brand-name">Glimmer</span>
</a>
<div>
<a href="/" class="btn btn-secondary btn-sm">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25"/></svg>
Home
</a>
</div>
</header>
<main class="main-wrapper">
<div class="center-page">
<p class="big-number">404</p>
<h2>Page Not Found</h2>
<p>The page you're looking for doesn't exist or may have been removed.</p>
<a href="/" class="btn btn-primary action">Go Home</a>
</div>
</main>
</div>
</body>
</html>
+154 -191
View File
@@ -1,197 +1,160 @@
<!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 — Glimmer</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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>
<a href="/admin/uploads" class="tab-link">Uploads</a>
</div>
<main class="container" style="max-width:960px">
{{define "title"}}Admin — Glimmer{{end}}
{{define "content"}}
<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>
<div class="page-header">
<div class="page-title">
<h1>Dashboard</h1>
<p>Overview of your short links and recent activity.</p>
</div>
<div class="page-actions">
<a href="/" class="btn btn-primary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:18px;height:18px"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
New Link
</a>
</div>
</div>
{{if .TopLinks}}
<article>
<header>
<h3>Quick Links</h3>
</header>
<div class="tile-grid">
{{range .TopLinks}}
<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>
</a>
{{end}}
</div>
</article>
{{end}}
{{if .Success}}
<div class="alert alert-success">{{.Success}}</div>
{{end}}
{{if .Success}}
<article aria-label="success" class="alert-success">{{.Success}}</article>
{{end}}
<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>
<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>
<button type="button" class="outline" onclick="showQR('/{{.Slug}}')">QR</button>
<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>
{{if .TopLinks}}
<section style="margin-bottom: 2rem;">
<div class="section-header">
<div>
<h2 class="section-title">Quick Links</h2>
<p class="section-subtitle">Top 20 most-clicked links — one click to open.</p>
</div>
</div>
<div class="tile-grid">
{{range .TopLinks}}
<a href="/{{.Slug}}" class="tile" target="_blank" rel="noopener noreferrer" title="{{.URL}}">
<span class="tile-slug">/{{.Slug}}</span>
<span class="tile-dest" data-hostname>{{.URL}}</span>
<span class="tile-clicks">{{.Clicks}} clicks</span>
</a>
{{end}}
</div>
</section>
{{end}}
<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>
<button type="button" class="outline" onclick="showQR('/{{.Slug}}')">QR</button>
<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>
<section style="margin-bottom: 2rem;">
<div class="section-header">
<div>
<h2 class="section-title">My Links</h2>
<p class="section-subtitle">{{len .AdminLinks}} links created by you.</p>
</div>
</div>
<div class="card card-flush">
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th>Slug</th>
<th>Destination</th>
<th class="col-numeric">Clicks</th>
<th>Created</th>
<th class="col-actions">Actions</th>
</tr>
</thead>
<tbody>
{{range .AdminLinks}}
<tr>
<td><a href="/{{.Slug}}" target="_blank" rel="noopener noreferrer">/{{.Slug}}</a></td>
<td title="{{.URL}}"><span class="text-truncate" style="display:inline-block;max-width:340px;vertical-align:middle">{{.URL}}</span></td>
<td class="col-numeric">{{.Clicks}}</td>
<td>{{.CreatedAt.Format "2006-01-02 15:04"}}</td>
<td class="col-actions">
<div class="flex gap-1">
<a href="/admin/edit/{{.ID}}" class="btn btn-secondary btn-sm">Edit</a>
<button type="button" class="btn btn-secondary btn-sm js-qr" data-slug="{{.Slug}}">QR</button>
<form method="post" action="/admin/delete/{{.ID}}" style="display:inline" data-confirm="Delete /{{.Slug}}?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr><td colspan="5">
<div class="empty-state">
<span class="empty-state-icon">🔗</span>
<p class="empty-state-text">No links yet.</p>
<a href="/" class="btn btn-primary btn-sm empty-state-action">Create your first link</a>
</div>
</td></tr>
{{end}}
</tbody>
</table>
</div>
</div>
</section>
</main>
<dialog id="qr-dialog">
<article>
<header>
<button aria-label="Close" rel="prev" onclick="document.getElementById('qr-dialog').close()"></button>
<h3>QR Code</h3>
</header>
<div id="qr-container" style="text-align:center"></div>
</article>
</dialog>
<script>
document.querySelectorAll('.tile-dest').forEach(el => {
try { el.textContent = new URL(el.textContent.trim()).hostname; } catch(e) {}
});
function showQR(slug) {
var container = document.getElementById('qr-container');
container.innerHTML = '<p>Loading...</p>';
document.getElementById('qr-dialog').showModal();
fetch('/admin/qr' + slug)
.then(function(r) { return r.text(); })
.then(function(svg) {
container.innerHTML = svg +
'<p style="margin-top:0.5rem;word-break:break-all">' + location.origin + slug + '</p>';
});
}
</script>
</body>
</html>
<section style="margin-bottom: 2rem;">
<div class="section-header">
<div>
<h2 class="section-title">Anonymous Links</h2>
<p class="section-subtitle">{{len .AnonLinks}} links created by unauthenticated users.</p>
</div>
</div>
<div class="card card-flush">
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th>Slug</th>
<th>Destination</th>
<th class="col-numeric">Clicks</th>
<th>Created</th>
<th class="col-actions">Actions</th>
</tr>
</thead>
<tbody>
{{range .AnonLinks}}
<tr>
<td><a href="/{{.Slug}}" target="_blank" rel="noopener noreferrer">/{{.Slug}}</a></td>
<td title="{{.URL}}"><span class="text-truncate" style="display:inline-block;max-width:340px;vertical-align:middle">{{.URL}}</span></td>
<td class="col-numeric">{{.Clicks}}</td>
<td>{{.CreatedAt.Format "2006-01-02 15:04"}}</td>
<td class="col-actions">
<div class="flex gap-1">
<a href="/admin/edit/{{.ID}}" class="btn btn-secondary btn-sm">Edit</a>
<button type="button" class="btn btn-secondary btn-sm js-qr" data-slug="{{.Slug}}">QR</button>
<form method="post" action="/admin/delete/{{.ID}}" style="display:inline" data-confirm="Delete /{{.Slug}}?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr><td colspan="5">
<div class="empty-state">
<span class="empty-state-icon">👥</span>
<p class="empty-state-text">No anonymous links.</p>
</div>
</td></tr>
{{end}}
</tbody>
</table>
</div>
</div>
</section>
<script src="/static/js/admin.js"></script>
{{end}}
+79 -179
View File
@@ -1,184 +1,84 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pastes — Admin</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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>
<a href="/admin/uploads" class="tab-link">Uploads</a>
</div>
<main class="container" style="max-width:1180px">
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
{{define "title"}}Pastes — Admin{{end}}
{{define "content"}}
<div class="section-header" style="padding-left:0;padding-right:0">
<hgroup>
<h2>Pastes</h2>
<p>{{len .Pastes}} pastes</p>
</hgroup>
<a href="/admin/bin/new" role="button" class="btn-sm">+ New Paste</a>
</div>
<div class="page-header">
<div class="page-title">
<h1>Pastes</h1>
<p>{{len .Pastes}} paste{{if ne (len .Pastes) 1}}s{{end}} — Markdown &amp; plain text, optionally token-protected.</p>
</div>
<div class="page-actions">
<a href="/admin/bin/new" class="btn btn-primary">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:18px;height:18px"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
New Paste
</a>
</div>
</div>
{{if .Pastes}}
<div class="pcard-grid">
{{range .Pastes}}
<article class="pcard js-preview" data-name="{{.Name}}" data-token="{{.Token}}" data-title="{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}" role="button" tabindex="0">
{{if .ThumbURL}}
<div class="pcard-imgwrap">
<img class="pcard-img" src="{{.ThumbURL}}" alt="" loading="lazy">
</div>
{{end}}
<div class="pcard-body">
<h3 class="pcard-title">{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}</h3>
{{if .Summary}}<p class="pcard-summary">{{.Summary}}</p>{{end}}
<div class="pcard-meta">
<mark class="badge-format">{{.Format}}</mark>
{{if .Token}}<mark class="badge-token">&#128274;</mark>{{else}}<mark class="badge-public">public</mark>{{end}}
{{if .Hidden}}<mark class="badge-hidden">hidden</mark>{{end}}
<span class="pcard-date">{{.UpdatedAt.Format "01-02 15:04"}}</span>
</div>
<div class="pcard-actions" role="group">
<button type="button" class="outline" onclick="copyPasteLink('{{.Name}}','{{.Token}}', this)">Copy link</button>
<a href="/admin/bin/edit/{{.ID}}" role="button" class="outline">Edit</a>
<button type="button" class="outline" onclick="showBinQR('{{.Name}}', false)">QR</button>
<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>
</div>
</article>
{{end}}
</div>
{{else}}
<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>
{{end}}
</main>
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{end}}
<dialog id="preview-dialog" class="preview-dialog">
<div class="preview-head">
<span class="preview-title" id="preview-title">Preview</span>
<div class="preview-actions">
<a id="preview-open" href="#" target="_blank" rel="noopener" role="button" class="outline btn-sm">Open &#8599;</a>
<button type="button" class="outline btn-sm" id="preview-expand" onclick="toggleExpand()" aria-label="Expand">&#8690;</button>
<button type="button" class="btn-sm preview-close" onclick="closePreview()" aria-label="Close">&#10005;</button>
</div>
</div>
<iframe id="preview-frame" class="preview-frame" src="about:blank" title="Paste preview"></iframe>
</dialog>
<dialog id="qr-dialog">
<article>
<header>
<button aria-label="Close" rel="prev" onclick="document.getElementById('qr-dialog').close()"></button>
<h3 id="qr-title">QR Code</h3>
</header>
<div id="qr-container" style="text-align:center"></div>
</article>
{{if .Pastes}}
<div class="paste-grid">
{{range .Pastes}}
<article class="paste-card js-preview" data-name="{{.Name}}" data-token="{{.Token}}" data-title="{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}">
{{if .ThumbURL}}
<div class="paste-card-thumb">
<img src="{{.ThumbURL}}" alt="" loading="lazy">
</div>
{{else}}
<div class="paste-card-thumb">
<span class="paste-card-thumb-empty">{{.Format}}</span>
</div>
{{end}}
<div class="paste-card-body">
<h3 class="paste-card-title">{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}</h3>
{{if .Summary}}<p class="paste-card-summary">{{.Summary}}</p>{{end}}
<div class="paste-card-meta">
<span class="tag-pill badge-format">{{.Format}}</span>
{{if .Token}}
<span class="tag-pill badge-token">🔒</span>
{{else}}
<span class="tag-pill badge-public">public</span>
{{end}}
{{if .Hidden}}<span class="tag-pill badge-hidden">hidden</span>{{end}}
<span class="paste-card-date">{{.UpdatedAt.Format "01-02 15:04"}}</span>
</div>
</div>
<div class="paste-card-actions">
<button type="button" class="btn btn-secondary btn-sm js-copy-link">Copy link</button>
<a href="/admin/bin/edit/{{.ID}}" class="btn btn-secondary btn-sm">Edit</a>
<button type="button" class="btn btn-secondary btn-sm js-bin-qr">QR</button>
<form method="post" action="/admin/bin/delete/{{.ID}}" style="display:inline" data-confirm="Delete paste {{.Name}}?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
</div>
</article>
{{end}}
</div>
{{else}}
<div class="card">
<div class="empty-state">
<span class="empty-state-icon">📄</span>
<p class="empty-state-text">No pastes yet.</p>
<a href="/admin/bin/new" class="btn btn-primary empty-state-action">Create your first paste</a>
</div>
</div>
{{end}}
<!-- Paste preview dialog -->
<dialog id="preview-dialog" class="preview-dialog">
<div class="preview-head">
<span class="preview-title" id="preview-title">Preview</span>
<div class="preview-actions">
<a id="preview-open" href="#" target="_blank" rel="noopener" class="btn btn-secondary btn-sm">Open ↗</a>
<button type="button" class="btn btn-secondary btn-sm" id="preview-expand" aria-label="Expand">⤢</button>
<button type="button" class="btn btn-secondary btn-sm" id="preview-close" aria-label="Close">✕</button>
</div>
</div>
<iframe id="preview-frame" class="preview-frame" src="about:blank" title="Paste preview"></iframe>
</dialog>
<script>
function previewURL(name, token) {
var u = '/bin/' + encodeURIComponent(name);
if (token) u += '/' + encodeURIComponent(token);
return u;
}
function openPreview(name, token, title) {
var dlg = document.getElementById('preview-dialog');
var url = previewURL(name, token);
document.getElementById('preview-frame').src = url;
document.getElementById('preview-open').href = url;
document.getElementById('preview-title').textContent = title || name;
dlg.classList.remove('expanded');
document.getElementById('preview-expand').innerHTML = '&#8690;';
document.getElementById('preview-expand').setAttribute('aria-label', 'Expand');
dlg.showModal();
}
function closePreview() {
document.getElementById('preview-dialog').close();
}
function toggleExpand() {
var dlg = document.getElementById('preview-dialog');
var expanded = dlg.classList.toggle('expanded');
var btn = document.getElementById('preview-expand');
btn.innerHTML = expanded ? '&#8689;' : '&#8690;';
btn.setAttribute('aria-label', expanded ? 'Shrink' : 'Expand');
}
function copyPasteLink(name, token, btn) {
var url = location.origin + previewURL(name, token);
navigator.clipboard.writeText(url).then(function() {
var orig = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
// Clicking anywhere on a card opens the preview, except on the action
// buttons. Data attributes avoid quoting issues with paste titles.
document.querySelectorAll('.js-preview').forEach(function(el) {
el.addEventListener('click', function(e) {
if (e.target.closest('.pcard-actions')) return;
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
});
el.addEventListener('keydown', function(e) {
if ((e.key === 'Enter' || e.key === ' ') && !e.target.closest('.pcard-actions')) {
e.preventDefault();
openPreview(el.dataset.name, el.dataset.token, el.dataset.title);
}
});
});
// Clear the iframe when the dialog is dismissed via Esc / backdrop / button.
document.getElementById('preview-dialog').addEventListener('close', function() {
document.getElementById('preview-frame').src = 'about:blank';
});
function showBinQR(name, full) {
var container = document.getElementById('qr-container');
var title = document.getElementById('qr-title');
container.innerHTML = '<p>Loading...</p>';
title.textContent = full ? 'Full QR Code (with token)' : 'QR Code';
document.getElementById('qr-dialog').showModal();
var url = '/admin/bin/qr/' + encodeURIComponent(name);
if (full) url += '?full=1';
fetch(url)
.then(function(r) { return r.text(); })
.then(function(svg) {
var fullLink = location.origin + '/bin/' + name;
var note = '';
if (full) {
note = '<small style="color:var(--pico-muted-color)">(includes access token)</small>';
}
container.innerHTML = svg +
'<p style="margin-top:0.5rem;word-break:break-all">' + fullLink + '</p>' + note;
});
}
</script>
</body>
</html>
<script src="/static/js/admin_bin.js"></script>
{{end}}
+126 -184
View File
@@ -1,193 +1,135 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<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="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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>
<a href="/admin/uploads" class="tab-link">Uploads</a>
</div>
<main class="container" style="max-width:860px">
<article>
<header>
<h2>{{if .Paste}}Edit Paste{{else}}New Paste{{end}}</h2>
</header>
{{define "title"}}{{if .Paste}}Edit Paste{{else}}New Paste{{end}} — Admin{{end}}
{{define "content"}}
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
<div class="page-header">
<div class="page-title">
<h1>{{if .Paste}}Edit Paste{{else}}New Paste{{end}}</h1>
<p>{{if .Paste}}Update the content and access settings.{{else}}Write a new paste — Markdown or plain text, optionally token-protected.{{end}}</p>
</div>
<div class="page-actions">
<a href="/admin/bin" class="btn btn-secondary">Back to pastes</a>
</div>
</div>
{{if .Paste}}
{{with .Paste}}
<form method="post" action="/admin/bin/edit/{{.ID}}">
{{else}}{{end}}
{{else}}
<form method="post" action="/admin/bin/new">
{{end}}
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{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>
<div class="card">
{{if .Paste}}
{{with .Paste}}<form method="post" action="/admin/bin/edit/{{.ID}}">{{else}}{{end}}
{{else}}
<form method="post" action="/admin/bin/new">
{{end}}
<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>
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<label>Content</label>
<div class="upload-controls">
<button type="button" id="upload-img-btn" class="outline secondary" title="PNG, JPEG, GIF, WebP — up to 50 MB">Upload Image <small style="opacity:.7">(50 MB)</small></button>
<button type="button" id="upload-file-btn" class="outline secondary" title="Any file type — up to 5 MB">Upload File <small style="opacity:.7">(5 MB)</small></button>
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
<input type="file" id="file-input" style="display:none">
<small id="upload-status"></small>
</div>
{{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}}
<div class="form-row">
<div class="form-group">
<label for="name" class="form-label">Name <small class="text-muted">(URL slug)</small></label>
{{if .Paste}}
{{with .Paste}}<input type="text" id="name" name="name" value="{{.Name}}" required pattern="[a-zA-Z0-9_-]+" title="Letters, numbers, hyphens, underscores">{{end}}
{{else}}
<input type="text" id="name" name="name" required pattern="[a-zA-Z0-9_-]+" placeholder="my-script" title="Letters, numbers, hyphens, underscores">
{{end}}
<small class="form-help">Path: <code>/bin/<span id="name-preview">{{if .Paste}}{{with .Paste}}{{.Name}}{{end}}{{else}}...{{end}}</span></code></small>
</div>
<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 onchange="toggleCustomToken()"> Keep current token</label>
<label><input type="radio" name="token_action" value="regenerate" onchange="toggleCustomToken()"> Regenerate token</label>
<label><input type="radio" name="token_action" value="custom" onchange="toggleCustomToken()"> Set custom token</label>
<label><input type="radio" name="token_action" value="disable" onchange="toggleCustomToken()"> 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 onchange="toggleCustomToken()"> Keep disabled</label>
<label><input type="radio" name="token_action" value="regenerate" onchange="toggleCustomToken()"> Enable with new token</label>
<label><input type="radio" name="token_action" value="custom" onchange="toggleCustomToken()"> Set custom token</label>
{{end}}
<div id="custom-token-wrap" style="display:none;margin-left:2rem">
<input type="text" name="custom_token" placeholder="Enter custom token" pattern="[a-zA-Z0-9_-]+" maxlength="64">
</div>
<label style="margin-top:0.5rem">
<input type="checkbox" name="hidden" value="1" {{if .Hidden}}checked{{end}}>
Hide paste (return 404 if accessed without token)
</label>
{{end}}
{{else}}
<label><input type="radio" name="enable_token" value="0" checked onchange="toggleCustomToken()"> No token (public access)</label>
<label><input type="radio" name="enable_token" value="1" onchange="toggleCustomToken()"> Generate access token</label>
<label><input type="radio" name="enable_token" value="custom" onchange="toggleCustomToken()"> Custom token</label>
<div id="custom-token-wrap" style="display:none;margin-left:2rem">
<input type="text" name="custom_token" placeholder="Enter custom token" pattern="[a-zA-Z0-9_-]+" maxlength="64">
</div>
<label style="margin-top:0.5rem">
<input type="checkbox" name="hidden" value="1">
Hide paste (return 404 if accessed without token)
</label>
{{end}}
</fieldset>
<div class="form-group">
<label for="title" class="form-label">Title <small class="text-muted">(optional)</small></label>
{{if .Paste}}
{{with .Paste}}<input type="text" id="title" name="title" value="{{.Title}}" placeholder="A short description">{{end}}
{{else}}
<input type="text" id="title" name="title" placeholder="A short description">
{{end}}
</div>
</div>
<div role="group" style="margin-top:1rem">
<button type="submit">Save</button>
<a href="/admin/bin" role="button" class="outline secondary">Cancel</a>
</div>
<div class="form-group">
<label for="format" class="form-label">Format</label>
<select id="format" 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>
</div>
<div class="form-group">
<label for="content" class="form-label">Content</label>
<div class="upload-controls" style="margin-bottom: 0.5rem;">
<button type="button" id="upload-img-btn" class="btn btn-secondary btn-sm" data-max-mb="{{$.UploadMaxMB}}" title="PNG, JPEG, GIF, WebP — up to 50 MB">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>
Upload Image
</button>
<button type="button" id="upload-file-btn" class="btn btn-secondary btn-sm" title="Any file type — up to 5 MB">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"/></svg>
Upload File
</button>
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
<input type="file" id="file-input" style="display:none">
<small id="upload-status" class="upload-status"></small>
</div>
{{if .Paste}}
{{with .Paste}}<textarea id="content" name="content" rows="20">{{.Content}}</textarea>{{end}}
{{else}}
<textarea id="content" name="content" rows="20" placeholder="# Hello&#10;&#10;Write your markdown here..."></textarea>
{{end}}
</div>
<fieldset>
<legend>Access Token</legend>
{{if .Paste}}
{{with .Paste}}
{{if .Token}}
<p class="text-muted" style="margin-bottom: 0.75rem;">
Current token: <code>{{.Token}}</code> — 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="custom"> Set custom token</label>
<label><input type="radio" name="token_action" value="disable"> Disable token (public access)</label>
{{else}}
<p class="text-muted" style="margin-bottom: 0.75rem;">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>
<label><input type="radio" name="token_action" value="custom"> Set custom token</label>
{{end}}
<div id="custom-token-wrap" style="display:none; margin: 0.5rem 0 0.5rem 1.5rem;">
<input type="text" name="custom_token" placeholder="Enter custom token" pattern="[a-zA-Z0-9_-]+" maxlength="64">
</div>
<label style="margin-top: 0.5rem;">
<input type="checkbox" name="hidden" value="1" {{if .Hidden}}checked{{end}}>
Hide paste (return 404 if accessed without token)
</label>
{{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>
<label><input type="radio" name="enable_token" value="custom"> Custom token</label>
<div id="custom-token-wrap" style="display:none; margin: 0.5rem 0 0.5rem 1.5rem;">
<input type="text" name="custom_token" placeholder="Enter custom token" pattern="[a-zA-Z0-9_-]+" maxlength="64">
</div>
<label style="margin-top: 0.5rem;">
<input type="checkbox" name="hidden" value="1">
Hide paste (return 404 if accessed without token)
</label>
{{end}}
</fieldset>
<div class="flex gap-1" style="margin-top: 1.5rem;">
<button type="submit" class="btn btn-primary btn-lg">Save paste</button>
<a href="/admin/bin" class="btn btn-secondary btn-lg">Cancel</a>
</div>
</form>
{{if .Paste}}{{with .Paste}}{{end}}{{end}}
</div>
</form>
{{if .Paste}}{{with .Paste}}{{end}}{{end}}
</article>
</main>
<script src="/static/upload.js"></script>
<script>
function toggleCustomToken() {
var wrap = document.getElementById('custom-token-wrap');
if (!wrap) return;
var checked = document.querySelector('input[name="token_action"][value="custom"]:checked') ||
document.querySelector('input[name="enable_token"][value="custom"]:checked');
wrap.style.display = checked ? 'block' : 'none';
}
(function() {
var textarea = document.querySelector('textarea[name="content"]');
var status = document.getElementById('upload-status');
function insertAtCursor(text) {
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var before = textarea.value.substring(0, start);
var after = textarea.value.substring(end);
textarea.value = before + text + '\n' + after;
textarea.selectionStart = textarea.selectionEnd = start + text.length + 1;
textarea.focus();
}
var uploader = window.GlimmerUpload.init({
imgBtn: document.getElementById('upload-img-btn'),
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: status,
maxImageMB: {{.UploadMaxMB}},
onUploaded: function(data) {
insertAtCursor(data.markdown);
status.textContent = 'Uploaded';
setTimeout(function() { status.textContent = ''; }, 3000);
}
});
textarea.addEventListener('paste', function(e) {
var items = (e.clipboardData || {}).items || [];
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
e.preventDefault();
uploader.doUpload(items[i].getAsFile(), true);
return;
}
}
});
})();
</script>
</body>
</html>
<script src="/static/js/admin_bin_edit.js"></script>
{{end}}
+43 -48
View File
@@ -1,52 +1,47 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Edit Link — Glimmer</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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>
{{define "title"}}Edit Link — Glimmer{{end}}
{{define "content"}}
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
<div class="page-header">
<div class="page-title">
<h1>Edit Link</h1>
<p>Update the slug or destination URL.</p>
</div>
<div class="page-actions">
<a href="/admin" class="btn btn-secondary">Back to list</a>
</div>
</div>
{{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">
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{end}}
<label for="url">Destination URL</label>
<input type="url" id="url" name="url" value="{{.URL}}" required>
{{with .Link}}
<div class="card" style="max-width: 640px;">
<form method="post" action="/admin/edit/{{.ID}}">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<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>
<div class="form-group">
<label for="slug" class="form-label">Slug</label>
<input type="text" id="slug" name="slug" value="{{.Slug}}" required pattern="[a-zA-Z0-9_-]+" title="Letters, numbers, hyphens, underscores only">
<small class="form-help">The short path users will visit: <code>/<span id="slug-preview">{{.Slug}}</span></code></small>
</div>
<div class="form-group">
<label for="url" class="form-label">Destination URL</label>
<input type="url" id="url" name="url" value="{{.URL}}" required>
</div>
<hr class="divider">
<div class="flex gap-1">
<button type="submit" class="btn btn-primary">Save changes</button>
<a href="/admin" class="btn btn-secondary">Cancel</a>
</div>
</form>
</div>
<script src="/static/js/admin_edit.js"></script>
{{else}}
<div class="alert alert-error">Link not found.</div>
{{end}}
{{end}}
+33 -34
View File
@@ -1,44 +1,43 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{.CSRFToken}}">
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Login — Glimmer</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
<title>Admin Login — Glimmer</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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>
<body class="login-container">
<div class="login-card">
<div class="login-header">
<div class="brand">
<div class="brand-logo">G</div>
<span class="brand-name">Glimmer</span>
</div>
<h2>Admin Login</h2>
<p>Sign in to manage your links</p>
</div>
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{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>
<form action="/admin/login" method="POST">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<div class="form-group">
<label for="username" class="form-label">Username</label>
<input type="text" id="username" name="username" placeholder="admin" required autofocus>
</div>
<button type="submit">Log in</button>
</form>
</article>
</div>
</main>
<div class="form-group" style="margin-bottom: 1.75rem;">
<label for="password" class="form-label">Password</label>
<input type="password" id="password" name="password" placeholder="••••••••" required>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Log in</button>
</form>
</div>
</body>
</html>
+111 -187
View File
@@ -1,191 +1,115 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Uploads — Admin</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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">Pastes</a>
<a href="/admin/uploads" class="tab-link active">Uploads</a>
</div>
<main class="container" style="max-width:960px">
{{if .Error}}
<article aria-label="error" class="alert-error">{{.Error}}</article>
{{end}}
{{define "title"}}Uploads — Admin{{end}}
{{define "content"}}
<article class="card-table">
<div class="section-header">
<hgroup>
<h2>Uploads</h2>
<p>{{len .Uploads}} files</p>
</hgroup>
<div class="upload-controls">
<button type="button" id="upload-img-btn" class="btn-sm" title="PNG, JPEG, GIF, WebP — up to 50 MB">Upload Image <small style="opacity:.7">(50 MB)</small></button>
<button type="button" id="upload-file-btn" class="btn-sm outline" title="Any file type — up to 5 MB">Upload File <small style="opacity:.7">(5 MB)</small></button>
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
<input type="file" id="file-input" style="display:none">
<small id="upload-status"></small>
</div>
</div>
<figure>
<table role="grid">
<thead>
<tr>
<th>Preview</th>
<th>File</th>
<th>Size</th>
<th>Dimensions</th>
<th>Uploaded</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{range .Uploads}}
<tr>
<td>
{{if .IsImage}}<a href="{{.URL}}" target="_blank"><img src="{{.URL}}" style="max-width:72px;max-height:52px;object-fit:contain;border-radius:4px"></a>
{{else}}<a href="{{.URL}}" target="_blank" style="font-size:1.5rem" title="Download file">&#128196;</a>
{{end}}
</td>
<td>
<div style="display:flex;align-items:center;gap:.4rem;flex-wrap:wrap">
<span class="ext-chip">{{.Ext}}</span>
{{if .OriginalName}}<span style="font-size:0.85rem">{{.OriginalName}}</span>{{end}}
</div>
<code style="font-size:0.7rem;opacity:.6">{{.Filename}}</code>
</td>
<td id="size-{{.Filename}}">{{.SizeHuman}}</td>
<td id="dim-{{.Filename}}">{{if .Width}}{{.Width}}&times;{{.Height}}{{else}}&mdash;{{end}}</td>
<td>{{.ModTime.Format "2006-01-02 15:04"}}</td>
<td>
<div role="group">
<button type="button" class="outline btn-sm" onclick="copyMarkdown('{{.Filename}}', {{.IsImage}}, {{.OriginalName}}, this)">Copy</button>
{{if .CanResize}}<button type="button" class="outline btn-sm" onclick="openResize('{{.Filename}}', {{.Width}}, {{.Height}})">Resize</button>{{end}}
<form method="post" action="/admin/uploads/delete/{{.Filename}}" onsubmit="return confirm('Delete this file?')" style="margin:0">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="outline secondary btn-sm">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr>
<td colspan="6">
<div class="empty-state">
<span class="empty-icon">&#128196;</span>
<p>No uploads yet. Use the buttons above to upload an image or file.</p>
</div>
</td>
</tr>
{{end}}
</tbody>
</table>
</figure>
</article>
</main>
<div class="page-header">
<div class="page-title">
<h1>Uploads</h1>
<p>Manage your uploaded images and files. Use them in pastes via the markdown link.</p>
</div>
<div class="page-actions">
<a href="/admin/bin" class="btn btn-secondary">Back to pastes</a>
</div>
</div>
<dialog id="resize-dialog">
<article>
<header>
<button aria-label="Close" rel="prev" onclick="document.getElementById('resize-dialog').close()"></button>
<h3>Resize Image</h3>
</header>
<p id="resize-current" style="color:var(--pico-muted-color)"></p>
<label>
Max dimension (px)
<input type="number" id="resize-dim" value="1200" min="64" max="8192" step="1">
</label>
<small id="resize-status" style="color:var(--pico-muted-color)"></small>
<footer>
<button type="button" class="secondary outline" onclick="document.getElementById('resize-dialog').close()">Cancel</button>
<button type="button" id="resize-confirm">Resize</button>
</footer>
</article>
</dialog>
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{end}}
<div class="card card-flush">
<div class="card-header">
<div>
<h2 class="card-title">All uploads</h2>
<p class="card-subtitle">{{len .Uploads}} file{{if ne (len .Uploads) 1}}s{{end}} stored locally.</p>
</div>
<div class="upload-controls">
<button type="button" id="upload-img-btn" class="btn btn-primary btn-sm" data-max-mb="{{.UploadMaxMB}}" title="PNG, JPEG, GIF, WebP — up to 50 MB">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>
Upload Image <small style="opacity:.6">(50 MB)</small>
</button>
<button type="button" id="upload-file-btn" class="btn btn-secondary btn-sm" title="Any file type — up to 5 MB">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M18.375 12.739l-7.693 7.693a4.5 4.5 0 01-6.364-6.364l10.94-10.94A3 3 0 1119.5 7.372L8.552 18.32m.009-.01l-.01.01m5.699-9.941l-7.81 7.81a1.5 1.5 0 002.112 2.13"/></svg>
Upload File <small style="opacity:.6">(5 MB)</small>
</button>
<input type="file" id="img-input" accept="image/png,image/jpeg,image/gif,image/webp" style="display:none">
<input type="file" id="file-input" style="display:none">
<small id="upload-status" class="upload-status"></small>
</div>
</div>
<div class="data-table-wrapper">
<table class="data-table">
<thead>
<tr>
<th style="width: 90px;">Preview</th>
<th>File</th>
<th>Size</th>
<th>Dimensions</th>
<th>Uploaded</th>
<th class="col-actions">Actions</th>
</tr>
</thead>
<tbody>
{{range .Uploads}}
<tr>
<td>
{{if .IsImage}}
<a href="{{.URL}}" target="_blank" rel="noopener noreferrer">
<img src="{{.URL}}" style="max-width:72px; max-height:52px; object-fit:contain; border-radius:4px; border:1px solid var(--color-border)" alt="">
</a>
{{else}}
<a href="{{.URL}}" target="_blank" rel="noopener noreferrer" style="font-size:1.5rem; text-decoration:none" title="Download file">📄</a>
{{end}}
</td>
<td>
<div style="display:flex; align-items:center; gap:0.5rem; flex-wrap:wrap;">
<span class="ext-chip">{{.Ext}}</span>
{{if .OriginalName}}<span style="font-size:0.9rem">{{.OriginalName}}</span>{{end}}
</div>
<code style="font-size:0.7rem; opacity:.6; display:block; margin-top:0.2rem;">{{.Filename}}</code>
</td>
<td id="size-{{.Filename}}">{{.SizeHuman}}</td>
<td id="dim-{{.Filename}}">{{if .Width}}{{.Width}}&times;{{.Height}}{{else}}—{{end}}</td>
<td>{{.ModTime.Format "2006-01-02 15:04"}}</td>
<td class="col-actions">
<div class="flex gap-1">
<button type="button" class="btn btn-secondary btn-sm js-copy-md" data-filename="{{.Filename}}" data-image="{{if .IsImage}}1{{end}}" data-original="{{.OriginalName}}">Copy</button>
{{if .CanResize}}<button type="button" class="btn btn-secondary btn-sm js-resize" data-filename="{{.Filename}}" data-width="{{.Width}}" data-height="{{.Height}}">Resize</button>{{end}}
<form method="post" action="/admin/uploads/delete/{{.Filename}}" style="display:inline" data-confirm="Delete this file?">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-danger btn-sm">Del</button>
</form>
</div>
</td>
</tr>
{{else}}
<tr><td colspan="6">
<div class="empty-state">
<span class="empty-state-icon">📄</span>
<p class="empty-state-text">No uploads yet. Use the buttons above to upload an image or file.</p>
</div>
</td></tr>
{{end}}
</tbody>
</table>
</div>
</div>
<dialog id="resize-dialog">
<article>
<header>
<button class="js-resize-cancel" aria-label="Close"></button>
<h3>Resize Image</h3>
</header>
<p id="resize-current" class="text-muted" style="margin-bottom: 1rem;"></p>
<label class="form-label" for="resize-dim">Max dimension (px)</label>
<input type="number" id="resize-dim" value="1200" min="64" max="8192" step="1">
<small id="resize-status" class="text-muted" style="display:block; margin-top:0.5rem;"></small>
<footer>
<button type="button" class="btn btn-secondary js-resize-cancel">Cancel</button>
<button type="button" id="resize-confirm" class="btn btn-primary">Resize</button>
</footer>
</article>
</dialog>
<script src="/static/upload.js"></script>
<script>
var currentResizeFile = '';
function copyMarkdown(filename, isImage, originalName, btn) {
var url = '/uploads/' + filename;
var label = originalName || filename;
var md = isImage ? '![](' + url + ')' : '[' + label + '](' + url + ')';
navigator.clipboard.writeText(md).then(function() {
var orig = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = orig; }, 1500);
});
}
function openResize(filename, w, h) {
currentResizeFile = filename;
document.getElementById('resize-current').textContent = 'Current: ' + w + '×' + h;
document.getElementById('resize-status').textContent = '';
document.getElementById('resize-confirm').disabled = false;
document.getElementById('resize-dialog').showModal();
}
document.getElementById('resize-confirm').addEventListener('click', function() {
var dim = document.getElementById('resize-dim').value;
var status = document.getElementById('resize-status');
var btn = this;
status.textContent = 'Resizing…';
btn.disabled = true;
var fd = new FormData();
fd.append('csrf_token', window.GlimmerUpload.getCsrfToken());
fd.append('max_dim', dim);
fetch('/admin/uploads/resize/' + currentResizeFile, { method: 'POST', body: fd, credentials: 'same-origin' })
.then(function(r) { return r.json(); })
.then(function(data) {
btn.disabled = false;
if (data.error) {
status.textContent = 'Error: ' + data.error;
return;
}
var sizeEl = document.getElementById('size-' + currentResizeFile);
var dimEl = document.getElementById('dim-' + currentResizeFile);
if (sizeEl) sizeEl.textContent = data.size_human;
if (dimEl) dimEl.textContent = data.width + '×' + data.height;
status.textContent = 'Done — ' + data.size_human;
var imgs = document.querySelectorAll('img[src="/uploads/' + currentResizeFile + '"]');
imgs.forEach(function(img) { img.src = '/uploads/' + currentResizeFile + '?t=' + Date.now(); });
})
.catch(function() {
btn.disabled = false;
status.textContent = 'Failed';
});
});
window.GlimmerUpload.init({
imgBtn: document.getElementById('upload-img-btn'),
fileBtn: document.getElementById('upload-file-btn'),
imgInput: document.getElementById('img-input'),
fileInput: document.getElementById('file-input'),
statusEl: document.getElementById('upload-status'),
maxImageMB: {{.UploadMaxMB}},
onUploaded: function() { location.reload(); }
});
</script>
</body>
</html>
<script src="/static/js/admin_uploads.js"></script>
{{end}}
+103
View File
@@ -0,0 +1,103 @@
{{define "base"}}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{.CSRFToken}}">
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<title>{{block "title" .}}Glimmer{{end}}</title>
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<div class="app-container {{if not .LoggedIn}}public-layout{{end}}">
{{if .LoggedIn}}
<aside class="sidebar">
<a href="/admin" class="brand">
<div class="brand-logo">G</div>
<span class="brand-name">Glimmer</span>
</a>
<nav>
<ul class="nav-list">
<li class="nav-item {{if eq .ActiveNav "links"}}active{{end}}">
<a href="/admin" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244"/></svg>
Links
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "pastes"}}active{{end}}">
<a href="/admin/bin" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"/></svg>
Pastes
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "uploads"}}active{{end}}">
<a href="/admin/uploads" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 001.5-1.5V6a1.5 1.5 0 00-1.5-1.5H3.75A1.5 1.5 0 002.25 6v12a1.5 1.5 0 001.5 1.5zm10.5-11.25h.008v.008h-.008V8.25zm.375 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z"/></svg>
Uploads
</a>
</li>
<li class="nav-item {{if eq .ActiveNav "shorten"}}active{{end}}">
<a href="/" class="nav-link">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
New Link
</a>
</li>
</ul>
</nav>
<div class="sidebar-footer">
<a href="/" class="btn btn-secondary btn-sm btn-block" style="justify-content:center">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25"/></svg>
Home
</a>
<form action="/admin/logout" method="POST" style="margin:0">
<input type="hidden" name="csrf_token" value="{{$.CSRFToken}}">
<button type="submit" class="btn btn-secondary btn-sm btn-block" style="justify-content:center">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75"/></svg>
Log out
</button>
</form>
</div>
</aside>
{{else}}
<header class="public-header">
<a href="/" class="public-brand">
<div class="brand-logo">G</div>
<span class="brand-name">Glimmer</span>
</a>
<div>
{{if .LoggedIn}}
<a href="/admin" class="btn btn-secondary btn-sm">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z"/></svg>
Admin
</a>
{{else}}
<a href="/admin/login" class="btn btn-secondary btn-sm">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"/></svg>
Admin
</a>
{{end}}
</div>
</header>
{{end}}
<main class="main-wrapper">
{{template "content" .}}
</main>
</div>
<!-- QR Code Preview Modal -->
<div id="qr-modal-overlay" class="qr-modal-overlay">
<div id="qr-modal-card" class="qr-modal-card">
<button id="qr-modal-close" class="qr-modal-close" aria-label="Close">&times;</button>
<h3>QR Code</h3>
<img id="qr-modal-image" class="qr-modal-image" src="" alt="QR Code">
<code id="qr-modal-link" class="qr-modal-link"></code>
<a id="qr-modal-download" download="" href="" class="btn btn-primary btn-block" style="font-size:0.9rem; text-align:center;">Download PNG</a>
</div>
</div>
<script src="/static/js/base.js"></script>
</body>
</html>{{end}}
+24 -41
View File
@@ -1,43 +1,26 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Access Token Required — Glimmer</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</a></strong></li></ul>
<ul><li><a href="/">Home</a></li></ul>
</nav>
<main class="container" style="max-width:480px;padding-top:4rem;text-align:center">
<p style="font-size:4rem;line-height:1;margin:0">&#128274;</p>
<h2 style="margin-top:0.5rem">Access Token Required</h2>
<p style="color:var(--pico-muted-color)">This paste is protected. Enter the access token to view it.</p>
{{define "title"}}Access Token Required — Glimmer{{end}}
{{define "content"}}
<div style="max-width: 480px; margin: 4rem auto 0;">
{{if .Error}}
<article aria-label="error" class="alert-error" style="text-align:left">{{.Error}}</article>
{{end}}
<div class="card" style="text-align: center; padding: 2.5rem 2rem;">
<div style="font-size: 3.5rem; line-height: 1; margin-bottom: 0.5rem;">🔒</div>
<h2 style="font-size: 1.5rem;">Access Token Required</h2>
<p class="text-muted" style="margin-bottom: 1.5rem;">This paste is protected. Enter the access token to view it.</p>
<form id="token-form" style="text-align:left;margin-top:1.5rem">
<label>
Token
<input type="text" id="token-input" required placeholder="Enter access token" autofocus>
</label>
<button type="submit" style="width:100%">View Paste</button>
</form>
</main>
<script>
document.getElementById('token-form').addEventListener('submit', function(e) {
e.preventDefault();
var token = document.getElementById('token-input').value.trim();
if (token) {
window.location.href = window.location.pathname + '/' + encodeURIComponent(token);
}
});
</script>
</body>
</html>
{{if .Error}}
<div class="alert alert-error" style="text-align: left;">{{.Error}}</div>
{{end}}
<form id="token-form" style="text-align: left;">
<div class="form-group">
<label for="token-input" class="form-label">Token</label>
<input type="text" id="token-input" placeholder="Enter access token" required autofocus>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">View Paste</button>
</form>
</div>
</div>
<script src="/static/js/bin_token.js"></script>
{{end}}
+41 -47
View File
@@ -1,49 +1,43 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<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="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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}}
{{define "title"}}{{if .Paste}}{{with .Paste}}{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}{{end}}{{else}}Paste{{end}} — Glimmer{{end}}
{{define "content"}}
{{with .Paste}}
<div style="max-width: 900px; margin: 0 auto;">
<div class="paste-body">
{{.PasteBody}}
</div>
<div class="paste-header">
<div>
<h2>{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}}</h2>
<div class="paste-meta">
<code>/bin/{{.Name}}</code>
<span class="tag-pill badge-format">{{.Format}}</span>
{{if .Token}}
<span class="tag-pill badge-token">🔒 token protected</span>
{{else}}
<span class="tag-pill badge-public">public</span>
{{end}}
<span class="text-muted">updated {{.UpdatedAt.Format "2006-01-02 15:04"}}</span>
</div>
</div>
<div class="paste-toolbar">
<a href="?raw=1" class="btn btn-secondary btn-sm">Raw</a>
<button id="copy-paste-btn" class="btn btn-primary btn-sm">Copy</button>
</div>
</div>
{{with .Paste}}
<pre id="paste-raw" style="display:none">{{.Content}}</pre>
{{end}}
</main>
</body>
</html>
<div class="card" style="padding: 2rem;">
<div class="paste-body">
{{$.PasteBody}}
</div>
</div>
<pre id="paste-raw" style="display:none">{{.Content}}</pre>
</div>
<script src="/static/js/bin_view.js"></script>
{{else}}
<div class="card center-page">
<h2>Paste not found</h2>
<p class="text-muted">This paste may have been deleted or is hidden.</p>
</div>
{{end}}
{{end}}
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{{with .Paste}}<title>{{if .Title}}{{.Title}}{{else}}{{.Name}}{{end}} — Glimmer Paste</title>{{end}}
<link rel="stylesheet" href="/static/css/style.css">
<style>
/* Strip the page chrome when embedded — no header/toolbar/card wrapper */
body { padding: 1.5rem; }
.embed-wrap { max-width: 820px; margin: 0 auto; }
</style>
</head>
<body>
<div class="embed-wrap">
{{with .Paste}}
<div class="paste-body">
{{$.PasteBody}}
</div>
{{end}}
</div>
</body>
</html>
+51 -59
View File
@@ -1,64 +1,56 @@
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Glimmer</title>
<link rel="stylesheet" href="/static/pico.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<nav>
<ul><li><strong><a href="/">Glimmer</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>
{{define "title"}}Glimmer{{end}}
{{define "content"}}
<div style="max-width: 640px; margin: 1.5rem auto 0;">
{{if .Error}}
<article aria-label="error" style="border-left: 4px solid var(--pico-del-color); padding: 0.75rem 1rem;">
{{.Error}}
</article>
{{end}}
<div class="card" style="text-align: center; padding: 2.5rem 2rem;">
<div class="brand" style="justify-content: center; margin-bottom: 1rem;">
<div class="brand-logo">G</div>
<span class="brand-name">Glimmer</span>
</div>
<h1 style="font-size: 1.75rem; margin-bottom: 0.5rem;">Shorten a URL</h1>
<p class="text-muted" style="margin-bottom: 2rem;">Paste a long URL and get a short link.</p>
{{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}}
{{if .Error}}
<div class="alert alert-error">{{.Error}}</div>
{{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 .ShortURL}}
<div class="alert alert-success" style="text-align:left;">
<div style="flex-grow: 1;">
<strong>Your short link is ready.</strong>
<p class="text-muted" style="font-size: 0.85rem; margin-top: 0.25rem; word-break: break-all;">{{.OriginalURL}}</p>
</div>
</div>
<div class="result-box">
<code id="short-url">{{.ShortURL}}</code>
<button id="copy-short-url" class="btn btn-secondary btn-sm">Copy</button>
</div>
{{if .QRSVG}}
<div class="qr-display">{{.QRSVG}}</div>
{{end}}
{{end}}
{{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}}
<form method="post" action="/shorten" id="shorten-form" style="text-align: left;">
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<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>
<div class="form-group">
<label for="url" class="form-label">URL to shorten</label>
<input type="text" inputmode="url" id="url" name="url" placeholder="https://example.com/very/long/url" required>
</div>
{{if .LoggedIn}}
<div class="form-group">
<label for="slug" class="form-label">Custom slug <small class="text-muted">(optional)</small></label>
<input type="text" id="slug" name="slug" placeholder="my-link" pattern="[a-zA-Z0-9_-]+" title="Letters, numbers, hyphens, underscores only">
<small class="form-help">Leave blank to auto-generate a 3-character slug.</small>
</div>
{{end}}
<button type="submit" class="btn btn-primary btn-lg btn-block">Shorten</button>
</form>
</div>
</div>
<script src="/static/js/index.js"></script>
{{end}}
+63
View File
@@ -0,0 +1,63 @@
# Hardening / Robustness Plan
> Progress: all five items done. Item 5 verified in a live browser session
> (every page exercised, zero console errors / CSP violations).
Follow-ups from the 2026-06-09 security review (fixes from that review already
landed in `962f5d9`). Status legend: ☐ todo · ◐ in progress · ☑ done
## 1. ☑ Image decompression-bomb guard
`generateThumbnail` and `handleAdminUploadResize` call `image.Decode` with no
dimension check. A valid small PNG can declare huge pixel dimensions and OOM
the RPi Zero (512 MB) on decode. `GET /uploads/thumb/{filename}` is public and
triggers generation on first request.
- Add a bounded decode helper: `image.DecodeConfig` first (header only),
reject anything over 24 MP, use `int64` math so the width×height product
cannot overflow 32-bit `int` on ARMv5.
- Use it in both `generateThumbnail` and the resize handler.
## 2. ☑ Graceful shutdown
`Start()` calls `ListenAndServe` directly; SIGTERM/Ctrl-C kills in-flight
requests and gives SQLite no chance to close cleanly.
- `signal.NotifyContext` for SIGINT/SIGTERM, then `srv.Shutdown` with a 10 s
timeout.
## 3. ☑ `Secure` flag on the CSRF cookie
The session cookie sets `Secure` via `isHTTPS()`; the `csrf` cookie never
does. Make `csrfToken` a `*Server` method and set `Secure: s.isHTTPS(r)`.
(Stays non-HttpOnly on purpose — `upload.js` reads it.)
## 4. ☑ Handler test coverage
`api_test.go` / `mcp_test.go` are thorough but the web handlers (auth, CSRF,
upload serving) have zero tests. Add `handlers_test.go` covering at least:
- unauthenticated `/admin/*` requests redirect to login
- state-changing POSTs without a CSRF token are rejected (incl. the resize
route fixed in `962f5d9`)
- `/uploads/{filename}`: invalid/traversal names 404; non-image files get
`Content-Disposition: attachment` + octet-stream
- login: wrong password → 401, correct → session cookie + redirect
- oversized-image rejection from item 1
## 5. ☑ Drop `'unsafe-inline'` from `script-src` (CSP)
Done: all inline `<script>` blocks and `on*=` attributes moved to per-page
files under `static/js/` (`base.js` carries shared chrome: QR modal,
`glimmerCopy`, `form[data-confirm]`). Template data is passed via `data-*`
attributes instead of `{{...}}` interpolation in JS. `script-src` is now
`'self'`; `style-src` keeps `'unsafe-inline'` for the `style=""` attributes.
Verified live: shorten flow, login, QR modal, paste editor (token radios,
name preview), paste cards (preview dialog, expand/close), public paste view,
token prompt redirect, uploads page — no console errors or CSP violations.
---
**Verification for each item:** `go build ./...`, `go vet ./...`,
`go test ./...` must pass; CLAUDE.md conventions apply (no new deps,
RPi-Zero-friendly memory use).