Compare commits

..

No commits in common. "a043b43a56ebf317110b098e3be45b1799475f37" and "2caf94aeb4d94de079913933c94cfd509a8a1173" have entirely different histories.

34 changed files with 84 additions and 3648 deletions

View File

@ -1,20 +1,14 @@
.git venv/
__pycache__/
*.pyc
.git/
.gitignore .gitignore
__pycache__
.pytest_cache
.venv
venv
*.md *.md
Dockerfile Dockerfile
docker-compose.yml docker-compose.yml
docker-compose.override.yml docker-compose.override.yml
.env .env
.dockerignore .dockerignore
.archllm-progress.json
*.meta.json
demo/
data/
store/ store/
uploads/ uploads/
tests/ tests/
ui/

6
.gitignore vendored
View File

@ -10,20 +10,14 @@ build/
# Virtual environment # Virtual environment
venv/ venv/
.venv/
# Local data (stored in Docker volumes) # Local data (stored in Docker volumes)
store/ store/
uploads/ uploads/
data/
# Environment (contains secrets) # Environment (contains secrets)
.env .env
# arch-llm build artifacts (per-module LLM provenance, progress)
.archllm-progress.json
*.meta.json
# OS # OS
.DS_Store .DS_Store
Thumbs.db Thumbs.db

View File

@ -1,71 +0,0 @@
# AGENTS.md
## Orientation
- This repo is a **spec-first** project. `schema.arch` (the signed arch-llm spec) is the
single source of truth for the backend. `paste_bin/` is generated from it and verified
against frozen owner tests; `ui/client.js` + `ui/openapi.json` are emitted from it
(deterministic, no LLM). The SPA (`ui/index.html`, `ui/app.js`) is the only
hand-maintained frontend code.
- The old Flask implementation still lives on `main` (single-file `app.py`). This branch
(`fastapi-port`) replaces it. Port report: repo wiki, **FastAPI port (arch-llm
pipeline)**.
## Hard rules
- **Never hand-edit `paste_bin/*.py`** (except `app.py`/glue if you understand the
deterministic-glue invariant) or `ui/client.js` / `ui/openapi.json`. Change `schema.arch`
(or the design session), re-sign, rebuild, re-emit. The next build overwrites
hand-edits.
- **Never weaken or modify `tests/`** — they are owner-authored ground truth, frozen into
`tests/manifest.json` for every build. A failing test means the spec or the generation
is wrong, not the test.
- The SPA must call **only** `window.PasteBinAPI` (the generated client). No hand-rolled
`fetch`, no hardcoded endpoints, no second copy of error literals except the
client-side-feedback mirror in `ui/app.js` (keep it in sync with `x-error-literals` when
re-emitting).
- Keep the deployed UI same-origin: API paths + SPA + contract artifacts under one origin
via `ui/Caddyfile`.
- Paste IDs: `^[a-f0-9]{16}$`. Validate before any filesystem access (path-traversal
guard).
- Image uploads: magic-byte validation (PNG/JPEG/GIF/BMP/WEBP-as-RIFF+`WEBP`@8..11/
TIFF); SVG rejected. Mimetype derived server-side from extension — never trust the
client's.
## Commands
```sh
# backend
docker build -t paste-bin .
docker run -d --name paste-bin -p 18900:8080 -v paste-bin-data:/app/data paste-bin
pytest # 51 owner tests
# spec pipeline (requires the arch-llm CLI + the `paste-bin` design session)
archllm build --session paste-bin --out /tmp/paste-bin-build # regenerate backend (signoff-gated)
archllm openapi paste-bin --client --out ui # re-emit contract artifacts
```
Editing the spec: prefer the arch-llm design session (canvas / spec-ops), which owns
`draft/schema.arch` + `draft/tests/`; `design paste-bin signoff` after edits, then
rebuild. Editing `schema.arch` in this repo directly also works — just re-run the build
against it (`archllm build schema.arch ...`) and update `signoff.yaml` provenance.
## Deploy notes
- Caddy 2.6.2 quirk: the `root` directive is site-level (a `root` inside a `handle`
block fails the Caddyfile adapter). `ui/Caddyfile` uses the flat idiom: `handle` per
API path (reverse proxy) + site-level `file_server`. Run it **from the `ui/`
directory** (`root * .` resolves against CWD): `cd ui && caddy run --config Caddyfile`.
- Backend container: uvicorn on `:8080` inside, data under `/app/data`
(`store/` metadata JSON, `<id>.txt` text content, `uploads/` image/file bytes).
Volume `paste-bin-data` persists it; `docker restart paste-bin` resets the in-process
rate limiter (10 uploads / 60 s per IP) but not the data.
- HEAD requests must work on API routes (Flask-compat; FastAPI needs an explicit
`methods=["GET", "HEAD"]` — the spec pins this).
## Verified state (provenance)
- Build r3 (2026-11-18, qwen27b): `status=ok`, 51/51 tests, 92.5% coverage, boot ok.
- Signoff: schema `07e1c8b9e27e…` / tests `ce3bef1efa30…` (see `signoff.yaml`).
- Live probe: 62/62 assertions green (headers, roundtrips, all 7 bug-fix cases,
400/404/413/429 with exact error strings, expiry-delete, restart persistence).

View File

@ -1,8 +1,20 @@
FROM python:3.14-slim AS deps FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt . WORKDIR /app
RUN pip install --no-cache-dir -r requirements.txt && pip install --no-cache-dir pytest ruff mypy pytest-cov
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM deps
COPY . . COPY . .
CMD ["uvicorn", "paste_bin.app:app", "--host", "0.0.0.0", "--port", "8000"]
RUN mkdir -p /app/uploads /app/store && \
adduser --disabled-password --no-create-home appuser && \
chown -R appuser:appuser /app
USER appuser
EXPOSE 8080
ENV PORT=8080
CMD gunicorn --bind 0.0.0.0:${PORT} --workers 4 --timeout 120 app:app

133
README.md
View File

@ -1,93 +1,76 @@
# paste-bin (FastAPI port) # paste-bin
A minimal, security-focused paste bin: share text, images, and files with expiring ## Demo
links. This branch is the **arch-llm/FastAPI port** of the Flask app that still lives on
`main`. It is built spec-first: a signed `.arch` spec is the single source of truth, the
backend is generated + verified against frozen owner tests, and the frontend client is
generated from the emitted OpenAPI contract.
Wiki: the full port report (ability matrix, bugs fixed, build history, live probe) is on <video src="demo.mp4" controls width="100%"></video>
the repo wiki — **FastAPI port (arch-llm pipeline)**.
## The pipeline
``` A minimal, security-focused paste bin: share text, images, and files with
schema.arch (signed spec) <- source of truth expiring links. Built with Flask and file-based storage (no database).
|
| arch-llm build --session paste-bin (LLM generation, deterministic glue,
v pytest verification, 80% coverage gate)
paste_bin/ (generated backend) <- verified: 51/51 owner tests, 92.5% coverage
|
| arch-llm openapi paste-bin --client --out ui
v
ui/openapi.json + ui/client.js <- deterministic contract emission (no LLM)
|
v
ui/index.html + ui/app.js <- SPA; calls ONLY window.PasteBinAPI
```
Nothing here is hand-maintained against a drifting API: the backend is verified from the ## Features
spec, the client is generated from the OpenAPI projection of the same spec, and the SPA
only touches the generated client's exported surface. Drift becomes a build failure
instead of a silent runtime break.
## Layout - Text, image, and file pastes with random 16-hex-char IDs
- Expiry options: 1 hour, 1 day, 1 week, 1 month, or never
- Automatic background cleanup of expired pastes
- Per-IP upload rate limiting (10 uploads / 60 s)
- Image magic-byte validation; SVG rejected (XSS prevention)
- Paste-ID format validation (blocks path traversal on read/delete)
- Security headers: CSP, HSTS, nosniff, frame deny, referrer policy
- Raw view, pretty view, and download endpoints per paste
| Path | What | ## Quick Start
|---|---|
| `schema.arch` | the signed spec (single source of truth) |
| `signoff.yaml` | owner signoff hashes over spec + tests (provenance) |
| `paste_bin/` | generated FastAPI backend (7 modules + glue) |
| `tests/` | owner-authored ground-truth tests (51 tests, **frozen**) + freeze manifest |
| `ui/` | SPA + emitted contract artifacts (`openapi.json`, `client.js`) + Caddyfile |
| `Dockerfile` / `requirements.txt` | canonical image (python:3.14-slim, uvicorn) |
## Quick start ```bash
```sh
# backend (canonical image; data in volumes)
docker build -t paste-bin .
docker run -d --name paste-bin -p 18900:8080 \
-v paste-bin-data:/app/data paste-bin
# API on http://127.0.0.1:18900 (GET / -> JSON index, GET /health, /pastes/...)
# tests
pip install -r requirements.txt pip install -r requirements.txt
pytest # 51 tests python app.py
# visit http://localhost:8080
# UI + API same-origin (Caddy reverse proxy; run from the ui/ directory)
cd ui && caddy run --config Caddyfile
# http://127.0.0.1:18901/index.html
``` ```
`ui/Caddyfile` proxies every path the OpenAPI doc declares (`/`, `/health`, `/pastes*`) ## Configuration
to the backend on `127.0.0.1:18900` and serves the SPA + contract artifacts same-origin.
## The API (contract) | Variable | Default | Description |
|----------|---------|-------------|
| `PORT` | `8080` | Web server port |
| `SECRET_KEY` | random | Flask secret key |
| `UPLOAD_FOLDER` | `./uploads` | Binary file storage |
| `STORE_FOLDER` | `./store` | Paste metadata + text content |
`GET /` JSON index · `GET /health` · `POST /pastes` (multipart: `paste_type`, `title`, ## Docker
`expiry`, `content` or `file`) · `GET /pastes/{paste_id}` view ·
`GET /pastes/{paste_id}/raw` · `GET /pastes/{paste_id}/download`.
Errors are JSON `{error: str}` with **pinned literals** (see `x-error-literals` in ```bash
`ui/openapi.json`): `Content cannot be empty`, `Invalid expiry`, `Invalid paste type`, docker build -t paste-bin .
`No file selected`, `Invalid image format`, `File content does not match image type.`, docker run -p 8080:8080 \
`File too large. Maximum size is 20 MB.`, `Too many uploads. Please wait.`, -v paste-uploads:/app/uploads \
`Paste not found`. Paste IDs match `^[a-f0-9]{16}$` (exported as `PasteBinAPI.PASTE_ID_RE`). -v paste-store:/app/store \
paste-bin
```
## Editing the project Or with compose (mounts persistent volumes):
The spec is the project. To change behavior: edit `schema.arch` (or the arch-llm design ```bash
session `paste-bin`), re-sign, rebuild, re-emit. Do **not** hand-edit `paste_bin/` or docker compose up -d
`ui/client.js` — the next build/emission overwrites them. See `AGENTS.md` for the ```
agent-facing rules and `../wiki` for the port history.
## Differences from the Flask original ## Tests
- JSON API instead of HTML templates (the old form posts map 1:1 onto the multipart ```bash
contract); routes namespaced `/pastes/...`; create returns `201` JSON (was 302). pip install -r requirements.txt pytest
- `/health` + JSON index added (the old app had no `/health`). pytest tests/ -v
- 7 old bugs fixed, not duped (file-type `/raw` 500, silent expiry default, AVI-as-webp, ```
stripped text content, leaking rate-limit state, trusted client mimetype, orphaned
`.tmp.*` files) — details on the wiki. Covers paste roundtrips, path-traversal blocking, SVG/magic-byte
- 62/62 live probe assertions green on the final build (r3). validation, expiry parsing, and rate-limit setup.
## Security Notes
- Uploads are stored under a random ID; extension preserved only for
downloads with `Content-Disposition: attachment`.
- Text pastes are served as `text/plain` (never rendered as HTML).
- Images are served with `X-Content-Type-Options: nosniff` + restrictive CSP.
- Paste IDs are validated against `^[a-f0-9]{16}$` before any filesystem
access, so crafted URLs cannot read or delete arbitrary files.
## License
MIT — see [LICENSE](LICENSE).

View File

@ -1,17 +0,0 @@
# demo/
`paste-bin-demo.mp4` — 58 s silent demo of the arch-llm pipeline behind this
branch: signed `schema.arch` → `archllm build` → auto-emitted
`openapi.json` + generated `client.js` → the UI, then four real pastes
proved byte-for-byte against the live r3 backend.
- 1920×1080 @ 30 fps, H.264, no audio track
- every id, byte count, and hex string on screen is real data from the
running backend (pastes `91868038152c4042`, `9aab1097cd934a01`,
`4cf7de63d0de495d`; the 404 card is the app's own pinned literal)
- QA record: [REVIEW.md](REVIEW.md) — `hyperframes check` green
(0 errors), 18 frame snapshots + per-composition seam strips verified
- source: HyperFrames project (`index.html` + `compositions/{hook,pipeline,
demo,proof,end}.html`), built with the app's own design tokens
Wiki page: [FastAPI port (arch-llm pipeline)](https://git.home.ms/jarianc/paste-bin/wiki/FastAPI%20port%20(arch-llm%20pipeline)).

View File

@ -1,68 +0,0 @@
# REVIEW — paste-bin demo (storyline #1)
QA record for the 58 s silent demo. Tooling: `hyperframes check` (0.9.69) +
frame snapshots OCR-verified against the local Unlimited-OCR VLM, with
pixel-level geometry checks via PIL (the VLM's bounding boxes are approximate;
pixel measurement is the source of truth for positions).
## check (final)
`npx hyperframes@0.9.69 check --no-cache --no-browser-gpu --no-craft`
| section | errors | warnings | notes |
|----------|--------|----------|-------|
| lint | 0 | 19 | all `gsap_repeated_fromto_without_baseline` + dense-track advisories on demo/proof beat fades — accepted (each beat fades out fully before the next fades in; verified in seam frames) |
| runtime | 0 | 0 | |
| layout | 0 | 0 | (earlier `content_overlap` + `escaped_container` errors fixed by giving stage wrappers real canvas coords and card-relative meta/actions) |
| motion | 0 | 0 | |
| contrast | 0 | 0 | (earlier 22 warnings fixed: faint `#5f6880` → `#82899b`, small accent text → `#eb526b`/`#ed637a`, Create button `#d13352` for 4.5:1 white) |
| audio | 0 | 0 | `audio_none` info — intended (silent demo) |
**Check passed.**
## Frame verification (18 snapshots, /tmp/opencode/hf-review/)
| t | scene | verified |
|-------|---------|----------|
| 2 s | hook | composer with real 5-line content, 265 chars, toast `created · 201` + `91868038152c4042`, View card |
| 5 s | hook | toast gone (window ends 4.9 s), chip visible in Recent |
| 9 s | pipeline | title + schema.arch node, "signed spec / source of truth" |
| 12 s | pipeline | n1+n2, 51/51 + 92.5% landed on build node |
| 15 s | pipeline | chain to openapi.json + client.js chips, "deterministic · no LLM" |
| 24 s | demo a | id 91868038152c4042, verbatim CRLF content, meta `type text · 265 chars`, actions |
| 27 s | demo a→b | transition |
| 28 s | demo b | **pixel-verified**: stage bg center x = 960.0, teal 64×64 img center (959.5, 485.5), 256 px box — content correctly centered in the 936 px stage (earlier "off-center" reading was VLM bbox artifact) |
| 31 s | demo c | id 4cf7de63d0de495d, demo-paste.bin, 4,096 B, real hex head `c8 5e 3a d1 … c8 58` |
| 32 s | demo c | same (hex head exact) |
| 35 s | demo c→d | mid-fade (beat d fades in 12.95–13.25 local) |
| 37 s | demo d | id 0000…0000, "Paste not found", "it expired, or the id is wrong", 404 badge, meta `404 · { "error": "Paste not found" }`, caption |
| 42 s | proof | kicker `proof — r3 final build · 9 LLM calls · status ok`, 500, `GET /pastes/{id}/raw`, bug #1 line |
| 45 s | proof | 200 (500 gone — flip complete), 62/62 (count-up done), live-probe label + sub |
| 48 s | proof | 200, 62/62, 7, all 7 bug lines verified incl. crop-OCR of line 4 "stripped text content" |
| 49 s | proof | static hold (identical frame to 48 s — expected, no motion in window) |
| 53 s | end | "The spec is the project." + sub; chips not yet out (start 53.8 s) — correct |
| 55 s | end | all 3 chips: repo / branch fastapi-port / wiki FastAPI port (arch-llm pipeline) |
## Seam / cut QA (per-composition --review)
- demo seam-04 (beat a→b gap, 26.5 s): stage interior empty — 6 foreign px out of
~100 k sampled. No ghosting; beat fade windows are disjoint by design
(a-out 4.32–4.50 / b-in 4.95–5.25 local, etc.).
- proof seam-03 (43.6 s): 200 alone, 500 fully faded, counter at 0/62
(count-up starts 0.2 s later) — flip is clean, no double-number artifact
beyond the intended 0.3 s crossfade.
- pipeline + end beat sheets: nodes/chips settle on their own windows, no
layout jumps (layout section of check is 0 errors at all samples).
## Known cosmetic notes (accepted)
- VLM misreads "4,096" as "4,896" in one transcript — source frame is correct
(deterministic render of `4,096 B`); OCR-model error, not a frame defect.
- 19 advisory lint findings are the repeated fromTo baselines on beat fades
(each pair fades out→in with a gap; resting state is the faded-out baseline,
which is the correct visual).
## Render
`npx hyperframes@0.9.69 render` — 1920×1080 @ 30 fps, 58 s, silent, looks quality.
Output: `demo/paste-bin-demo.mp4` in the repo (`fastapi-port` branch).

Binary file not shown.

View File

View File

@ -1,149 +0,0 @@
from fastapi import APIRouter, Body, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from paste_bin import headers, ratelimit, store, validate
from paste_bin.headers import security_headers
from paste_bin.ratelimit import UploadRateLimiter
from paste_bin.validate import check_image_magic, derive_mimetype, generate_paste_id, is_image_ext, is_text_ext, is_valid_paste_id, parse_expiry, sanitize_filename
from paste_bin.store import PasteStore
import os
import tempfile
from datetime import datetime, timezone
from fastapi import File, Form, Request, UploadFile
from fastapi.responses import Response
class ErrOut(BaseModel):
error: str
class PasteOut(BaseModel):
id: str
title: str
type: str
created_at: str
expires_at: str | None
view: str
raw: str
download: str
class ViewOut(BaseModel):
id: str
type: str
title: str
created_at: str
expires_at: str | None
content: str | None
filename: str | None
mimetype: str | None
class HealthOut(BaseModel):
status: str
class IndexOut(BaseModel):
service: str
endpoints: list[str]
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
try:
_store = PasteStore(store_dir=os.environ.get("STORE_FOLDER", "store"), upload_dir=os.environ.get("UPLOAD_FOLDER", "uploads"))
except OSError:
_store = PasteStore(store_dir=tempfile.mkdtemp(prefix="paste-store-"), upload_dir=tempfile.mkdtemp(prefix="paste-uploads-"))
_store.start_cleanup_loop()
_limiter = UploadRateLimiter()
paste_router = APIRouter()
def _secure(r): return r.url.scheme == "https"
def _err(r, s, m): return JSONResponse(status_code=s, content={"error": m}, headers=security_headers(is_secure=_secure(r)))
def _ok(r, s, p): return JSONResponse(status_code=s, content=p, headers=security_headers(is_secure=_secure(r)))
def _out(pid, title, ptype, created, exp): return {"id": pid, "title": title, "type": ptype, "created_at": created, "expires_at": exp, "view": f"/pastes/{pid}", "raw": f"/pastes/{pid}/raw", "download": f"/pastes/{pid}/download"}
def _load(r, pid):
m = _store.load_meta(pid)
if m is None or _store.is_expired(m):
if m is not None: _store.delete(pid)
return None, _err(r, 404, "Paste not found")
return m, None
def _ext(fn): return fn.rsplit(".", 1)[-1].lower() if "." in fn else ""
@paste_router.post("/pastes")
async def create_paste(request: Request, paste_type: str = Form("text"), title: str = Form(""), expiry: str = Form("1d"), content: str = Form(""), file: UploadFile | None = File(None)):
if not _limiter.allow(client_ip=request.client.host):
return _err(request, 429, "Too many uploads. Please wait.")
try:
exp = parse_expiry(expiry)
except ValueError:
return _err(request, 400, "Invalid expiry")
pid = generate_paste_id()
created = datetime.now(timezone.utc).isoformat()
if paste_type == "text":
if not content.strip():
return _err(request, 400, "Content cannot be empty")
_store.write_content(pid, content)
meta = {"type": "text", "title": title, "created_at": created, "expires_at": exp, "filename": None, "mimetype": None, "filepath": None}
_store.save_meta(pid, meta)
return _ok(request, 201, _out(pid, title, "text", created, exp))
if paste_type in ("image", "file"):
if file is None or not file.filename:
return _err(request, 400, "No file selected")
fn = sanitize_filename(file.filename)
if not fn:
return _err(request, 400, "No file selected")
ext = _ext(fn)
if paste_type == "image":
if not is_image_ext(fn):
return _err(request, 400, "Invalid image format")
head = await file.read(12)
if not check_image_magic(head, ext):
return _err(request, 400, "File content does not match image type.")
data = head + await file.read()
elif is_text_ext(fn):
_store.write_content(pid, (await file.read()).decode("utf-8", errors="replace"))
meta = {"type": "text", "title": title or fn, "created_at": created, "expires_at": exp, "filename": fn, "mimetype": None, "filepath": None}
_store.save_meta(pid, meta)
return _ok(request, 201, _out(pid, title or fn, "text", created, exp))
else:
data = await file.read()
if len(data) > MAX_UPLOAD_BYTES:
return _err(request, 413, "File too large. Maximum size is 20 MB.")
fp = _store.write_upload(pid, data, ext)
meta = {"type": paste_type, "title": title or fn, "created_at": created, "expires_at": exp, "filename": fn, "mimetype": derive_mimetype(ext), "filepath": fp}
_store.save_meta(pid, meta)
return _ok(request, 201, _out(pid, title or fn, paste_type, created, exp))
return _err(request, 400, "Invalid paste type")
@paste_router.api_route("/pastes/{paste_id}", methods=["GET", "HEAD"])
async def get_paste(request: Request, response: Response, paste_id: str):
meta, err = _load(request, paste_id)
if err: return err
if meta.get("type") == "text":
payload = {"id": paste_id, "type": meta.get("type"), "title": meta.get("title"), "created_at": meta.get("created_at"), "expires_at": meta.get("expires_at"), "content": _store.read_content(paste_id) or "", "filename": meta.get("filename"), "mimetype": None}
else:
payload = {"id": paste_id, "type": meta.get("type"), "title": meta.get("title"), "created_at": meta.get("created_at"), "expires_at": meta.get("expires_at"), "content": None, "filename": meta.get("filename"), "mimetype": meta.get("mimetype")}
response.headers.update(security_headers(is_secure=_secure(request)))
return payload
@paste_router.api_route("/pastes/{paste_id}/download", methods=["GET", "HEAD"])
async def download_paste(request: Request, paste_id: str):
meta, err = _load(request, paste_id)
if err: return err
if meta.get("type") == "text":
data = (_store.read_content(paste_id) or "").encode("utf-8")
fn = meta.get("filename") or "paste.txt"
mt = "text/plain"
else:
fp = meta.get("filepath")
if not fp or not os.path.isfile(fp): return _err(request, 404, "Paste not found")
with open(fp, "rb") as f: data = f.read()
fn = meta.get("filename")
mt = meta.get("mimetype")
h = security_headers(is_secure=_secure(request)); h["Content-Disposition"] = f'attachment; filename="{fn}"'
return Response(content=data, media_type=mt, headers=h)
@paste_router.api_route("/pastes/{paste_id}/raw", methods=["GET", "HEAD"])
async def raw_paste(request: Request, paste_id: str):
meta, err = _load(request, paste_id)
if err: return err
if meta.get("type") == "text":
data = (_store.read_content(paste_id) or "").encode("utf-8")
mt = "text/plain; charset=utf-8"
else:
fp = meta.get("filepath")
if not fp or not os.path.isfile(fp): return _err(request, 404, "Paste not found")
with open(fp, "rb") as f: data = f.read()
mt = meta.get("mimetype")
return Response(content=data, media_type=mt, headers=security_headers(is_secure=_secure(request)))
@paste_router.api_route("/health", methods=["GET", "HEAD"])
async def health(request: Request, response: Response):
response.headers.update(security_headers(is_secure=_secure(request)))
return {"status": "ok"}
@paste_router.api_route("/", methods=["GET", "HEAD"])
async def index(request: Request, response: Response):
response.headers.update(security_headers(is_secure=_secure(request)))
return {"service": "paste-bin", "endpoints": ["/pastes", "/health"]}

View File

@ -1,5 +0,0 @@
from fastapi import FastAPI
from paste_bin.api import paste_router
app = FastAPI(title="paste_bin")
app.include_router(paste_router)

View File

@ -1,8 +0,0 @@
import os
def get_config() -> dict:
return {
"store_folder": os.environ.get("STORE_FOLDER", "store"),
"upload_folder": os.environ.get("UPLOAD_FOLDER", "uploads"),
}

View File

@ -1,11 +0,0 @@
def security_headers(is_secure: bool = False) -> dict:
headers = {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Content-Security-Policy": "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'",
}
if is_secure:
headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
return headers

View File

@ -1,25 +0,0 @@
import time
class UploadRateLimiter:
def __init__(self, max_attempts: int = 10, window_seconds: int = 60):
self.max_attempts = max_attempts
self.window_seconds = window_seconds
self.attempts: dict[str, list[float]] = {}
def allow(self, client_ip: str) -> bool:
now = time.monotonic()
cutoff = now - self.window_seconds
for ip in list(self.attempts):
ts = self.attempts[ip]
if not ts or ts[-1] < cutoff:
del self.attempts[ip]
ts = self.attempts.get(client_ip)
if ts is None:
self.attempts[client_ip] = [now]
return True
ts[:] = [t for t in ts if t >= cutoff]
if len(ts) < self.max_attempts:
ts.append(now)
return True
return False

View File

@ -1,10 +0,0 @@
from pydantic import BaseModel
class Paste(BaseModel):
type: str
title: str
created_at: str
expires_at: str | None
filename: str | None
mimetype: str | None
filepath: str | None

View File

@ -1,122 +0,0 @@
from paste_bin import validate
from paste_bin.validate import check_image_magic, derive_mimetype, generate_paste_id, is_image_ext, is_text_ext, is_valid_paste_id, parse_expiry, sanitize_filename
import json
import os
import threading
import time
from datetime import datetime, timezone
class PasteStore:
def __init__(self, store_dir: str, upload_dir: str) -> None:
self.store_dir = store_dir
self.upload_dir = upload_dir
os.makedirs(store_dir, exist_ok=True)
os.makedirs(upload_dir, exist_ok=True)
def save_meta(self, paste_id: str, meta: dict) -> None:
final_path = os.path.join(self.store_dir, paste_id)
tmp_path = os.path.join(self.store_dir, f"{paste_id}.tmp.{os.getpid()}")
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(meta, f)
os.replace(tmp_path, final_path)
def load_meta(self, paste_id: str) -> dict | None:
if not is_valid_paste_id(paste_id):
return None
path = os.path.join(self.store_dir, paste_id)
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except (OSError, ValueError):
return None
return data if isinstance(data, dict) else None
def write_content(self, paste_id: str, content: str) -> None:
path = os.path.join(self.store_dir, f"{paste_id}.txt")
with open(path, "w", encoding="utf-8", newline="") as f:
f.write(content)
def read_content(self, paste_id: str) -> str | None:
path = os.path.join(self.store_dir, f"{paste_id}.txt")
try:
with open(path, "r", encoding="utf-8", newline="") as f:
return f.read()
except FileNotFoundError:
return None
def write_upload(self, paste_id: str, data: bytes, ext: str) -> str:
path = os.path.join(self.upload_dir, f"{paste_id}.{ext}")
with open(path, "wb") as f:
f.write(data)
return os.path.abspath(path)
def delete(self, paste_id: str) -> None:
meta = self.load_meta(paste_id)
self._remove(os.path.join(self.store_dir, paste_id))
self._remove(os.path.join(self.store_dir, f"{paste_id}.txt"))
filepath = meta.get("filepath") if meta else None
if isinstance(filepath, str) and filepath:
if not os.path.isabs(filepath):
filepath = os.path.join(self.upload_dir, filepath)
if os.path.isfile(filepath):
self._remove(filepath)
return
try:
for name in os.listdir(self.upload_dir):
if name.startswith(f"{paste_id}."):
self._remove(os.path.join(self.upload_dir, name))
except OSError:
pass
@staticmethod
def _remove(path: str | None) -> None:
if not path:
return
try:
if os.path.isfile(path):
os.remove(path)
except OSError:
pass
def is_expired(self, meta: dict) -> bool:
expires_at = meta.get("expires_at")
if not expires_at:
return False
try:
dt = datetime.fromisoformat(str(expires_at).replace("Z", "+00:00"))
except ValueError:
return False
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt < datetime.now(timezone.utc)
def cleanup_expired(self) -> int:
deleted = 0
for name in os.listdir(self.store_dir):
path = os.path.join(self.store_dir, name)
if not os.path.isfile(path):
continue
if ".tmp." in name:
self._remove(path)
continue
if name.endswith(".txt"):
continue
if not is_valid_paste_id(name):
continue
meta = self.load_meta(name)
if meta and self.is_expired(meta):
self.delete(name)
deleted += 1
return deleted
def start_cleanup_loop(self, interval: int = 300) -> None:
def run() -> None:
while True:
try:
self.cleanup_expired()
time.sleep(interval)
except Exception:
pass
threading.Thread(target=run, daemon=True).start()

View File

@ -1,103 +0,0 @@
from __future__ import annotations
import re
import uuid
from datetime import datetime, timedelta, timezone
ALLOWED_IMAGE_EXTENSIONS = {"png", "jpg", "jpeg", "gif", "bmp", "webp", "tiff"}
ALLOWED_TEXT_EXTENSIONS = {
"txt", "py", "js", "ts", "c", "cpp", "h", "java", "rb", "go", "rs", "md",
"json", "xml", "yaml", "yml", "html", "css", "sh", "log", "csv", "sql",
"ini", "cfg", "toml", "lua", "php", "swift", "kt", "scala", "r", "pl",
"hs", "zig", "nix",
}
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
_PASTE_ID_RE = re.compile(r"^[a-f0-9]{16}$")
def generate_paste_id() -> str:
return uuid.uuid4().hex[:16]
def is_valid_paste_id(paste_id: str) -> bool:
return bool(_PASTE_ID_RE.match(paste_id))
def sanitize_filename(filename: str) -> str:
name = filename
if "/" in name:
name = name.rsplit("/", 1)[-1]
if "\\" in name:
name = name.rsplit("\\", 1)[-1]
cleaned = []
for ch in name:
if ch.isascii() and (ch.isalpha() or ch.isdigit() or ch in "._-"):
cleaned.append(ch)
else:
cleaned.append("_")
return "".join(cleaned).lstrip(".")[:255]
def parse_expiry(expiry: str) -> str | None:
now = datetime.now(timezone.utc)
if expiry == "1h":
result = now + timedelta(hours=1)
elif expiry == "1d":
result = now + timedelta(days=1)
elif expiry == "1w":
result = now + timedelta(weeks=1)
elif expiry == "1m":
result = now + timedelta(days=30)
elif expiry == "forever":
return None
else:
raise ValueError(f"Unknown expiry: {expiry}")
return result.isoformat().replace("+00:00", "Z")
def check_image_magic(data: bytes, ext: str) -> bool:
if ext == "png":
return data.startswith(b"\x89PNG\r\n\x1a\n")
if ext == "jpg":
return data.startswith(b"\xff\xd8\xff")
if ext == "gif":
return data.startswith(b"GIF87a") or data.startswith(b"GIF89a")
if ext == "bmp":
return data.startswith(b"BM")
if ext == "webp":
return data[:4] == b"RIFF" and data[8:12] == b"WEBP"
if ext == "tiff":
return True
return False
def derive_mimetype(ext: str) -> str:
if ext == "png":
return "image/png"
if ext in {"jpg", "jpeg"}:
return "image/jpeg"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
if ext == "tiff":
return "image/tiff"
return "application/octet-stream"
def is_image_ext(filename: str) -> bool:
if "." not in filename:
return False
return filename.rsplit(".", 1)[1].lower() in ALLOWED_IMAGE_EXTENSIONS
def is_text_ext(filename: str) -> bool:
if "." not in filename:
return False
return filename.rsplit(".", 1)[1].lower() in ALLOWED_TEXT_EXTENSIONS

View File

@ -1,2 +0,0 @@
[pytest]
testpaths = tests

View File

@ -1,18 +1,3 @@
annotated-doc==0.0.7 flask==3.1.0
annotated-types==0.8.0 gunicorn==23.0.0
anyio==4.16.0 werkzeug==3.1.3
certifi==2026.10.23
click==8.5.1
fastapi==0.164.0
h11==0.16.0
httpcore==1.0.9
httpx==0.28.1
idna==3.20
opentelemetry-api==1.45.2
pydantic==2.14.3
pydantic_core==2.50.4
python-multipart==0.0.34
starlette==1.10.0
typing-inspection==0.4.5
typing_extensions==4.16.0
uvicorn==0.54.0

View File

@ -1,147 +0,0 @@
project paste_bin
language python
framework fastapi
entrypoint paste_bin/app.py:app
requirement fastapi
requirement python_multipart
requirement httpx
foreign FastAPI = fastapi.FastAPI
record Paste {
type: str
title: str
created_at: str
expires_at: str | None
filename: str | None
mimetype: str | None
filepath: str | None
desc "one paste's metadata, stored as JSON at store_dir/<id>; the on-disk JSON keys are EXACTLY these field names; type is 'text' | 'image' | 'file'; filepath set for image/file pastes (absolute path in upload_dir), None for text"
}
test tests/test_validate.py -> validate
test tests/test_store.py -> store
test tests/test_paste_api.py -> api suspects validate, store, ratelimit, headers
test tests/test_ratelimit.py -> ratelimit
test tests/test_headers.py -> headers
module paste_bin/validate.py
desc "pure validation helpers: paste ids, expiry parsing, filename sanitizing, image magic-byte checks, mimetype derivation; no I/O, no state"
desc "module constants: ALLOWED_IMAGE_EXTENSIONS = {png, jpg, jpeg, gif, bmp, webp, tiff}; ALLOWED_TEXT_EXTENSIONS = {txt, py, js, ts, c, cpp, h, java, rb, go, rs, md, json, xml, yaml, yml, html, css, sh, log, csv, sql, ini, cfg, toml, lua, php, swift, kt, scala, r, pl, hs, zig, nix}; MAX_UPLOAD_BYTES = 20 * 1024 * 1024"
function generate_paste_id() -> str:
desc "uuid4().hex[:16] — 16 lowercase hex chars"
function is_valid_paste_id(paste_id: str) -> bool:
desc "True only if paste_id matches ^[a-f0-9]{16}$ — anything else (path traversal, weird chars) is invalid"
function sanitize_filename(filename: str) -> str:
desc "werkzeug secure_filename equivalent: take the basename after the last '/' or '\\\\', replace every character that is not an ASCII letter, digit, dot, dash or underscore with '_', strip leading dots, cap at 255 chars; may return '' — callers reject empty"
function parse_expiry(expiry: str) -> str | None:
desc "map expiry key to an ISO-8601 UTC timestamp string: '1h' now+1 hour, '1d' now+1 day, '1w' now+1 week, '1m' now+30 days, 'forever' -> None; any other key raises ValueError (the old app silently defaulted unknown keys to 1 day — fixed)"
function check_image_magic(data: bytes, ext: str) -> bool:
desc "verify upload bytes start with the extension's magic prefix: png b'\\x89PNG\\r\\n\\x1a\\n', jpg b'\\xff\\xd8\\xff', gif b'GIF87a' or b'GIF89a', bmp b'BM', webp first 4 bytes b'RIFF' AND bytes 8..11 == b'WEBP' (old app checked only RIFF, which accepted AVI — fixed), tiff -> True (no magic check); any other ext -> False"
function derive_mimetype(ext: str) -> str:
desc "MIME type from the file extension ONLY (never from client input — old app trusted file.mimetype — fixed): png -> image/png, jpg and jpeg -> image/jpeg, gif -> image/gif, bmp -> image/bmp, webp -> image/webp, tiff -> image/tiff, anything else -> application/octet-stream"
function is_image_ext(filename: str) -> bool:
desc "True if the lowercase extension (text after the last '.') is in ALLOWED_IMAGE_EXTENSIONS; no dot -> False"
function is_text_ext(filename: str) -> bool:
desc "True if the lowercase extension (text after the last '.') is in ALLOWED_TEXT_EXTENSIONS; no dot -> False"
module paste_bin/store.py
desc "file-backed paste persistence: store_dir holds JSON metadata at <id> and text content at <id>.txt; upload_dir holds binary uploads at <id>.<ext>; all metadata writes are atomic"
desc "is_valid_paste_id is imported from paste_bin.validate at module top level — the single source of truth, never redefined or reimplemented locally"
class PasteStore:
desc "creates both directories if missing"
ctor (store_dir: str, upload_dir: str)
method save_meta(paste_id: str, meta: dict) -> None:
desc "write meta as JSON to store_dir/<paste_id>; atomic: write to <paste_id>.tmp.<pid> then os.replace onto the final name"
method load_meta(paste_id: str) -> dict | None:
desc "None unless is_valid_paste_id(paste_id) AND the file exists AND the JSON parses; corrupt or missing -> None (never raises)"
method write_content(paste_id: str, content: str) -> None:
desc "write the paste's text content verbatim (utf-8) to store_dir/<paste_id>.txt"
method read_content(paste_id: str) -> str | None:
desc "content of store_dir/<paste_id>.txt (utf-8) or None if the file is absent"
method write_upload(paste_id: str, data: bytes, ext: str) -> str:
desc "write bytes to upload_dir/<paste_id>.<ext> and return the saved path as stored (absolute)"
method delete(paste_id: str) -> None:
desc "remove the metadata file, the <paste_id>.txt content file, and — for image/file pastes — the uploaded file at meta['filepath'] (the exact Paste record key); each removed only if present; never raises"
method is_expired(meta: dict) -> bool:
desc "True when meta['expires_at'] is set and that UTC timestamp is in the past; unset/None -> False"
method cleanup_expired() -> int:
desc "scan store_dir; for every parseable metadata file that is expired, delete() it; also remove stale <id>.tmp.* files left by a crashed write (old app never cleaned those — fixed); skip <id>.txt content files; return the number of pastes deleted"
method start_cleanup_loop(interval: int = 300) -> None:
desc "start a daemon thread calling cleanup_expired() every `interval` seconds, swallowing all exceptions"
module paste_bin/ratelimit.py
desc "per-IP sliding-window rate limiter for paste uploads, in-process state"
class UploadRateLimiter:
desc "timestamps kept in self.attempts: dict[str, list[float]] (ip -> monotonic timestamps within the window)"
ctor (max_attempts: int = 10, window_seconds: int = 60)
method allow(client_ip: str) -> bool:
desc "sliding window: drop the ip's timestamps older than window_seconds; if the ip already has max_attempts remaining, record now and return True, else return False; also delete ip keys whose newest attempt is now older than the window so the state dict cannot grow unbounded (old app leaked one list per ip forever — fixed)"
module paste_bin/headers.py
desc "security response headers for every response"
function security_headers(is_secure: bool = False) -> dict:
desc "return a dict with exactly these header values: X-Content-Type-Options 'nosniff', X-Frame-Options 'DENY', X-XSS-Protection '1; mode=block', Referrer-Policy 'strict-origin-when-cross-origin', Content-Security-Policy exactly \"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'\" (this exact string — no trailing semicolon), and — only when is_secure — Strict-Transport-Security 'max-age=31536000; includeSubDomains'"
module paste_bin/api.py
desc "FastAPI multipart router over the store; at import time build a module-level PasteStore named _store from env STORE_FOLDER (default 'store') and env UPLOAD_FOLDER (default 'uploads') and call _store.start_cleanup_loop() on it; also a module-level UploadRateLimiter named _limiter constructed with bare class defaults — exactly `_limiter = UploadRateLimiter()` (10 attempts per 60s window; NO config indirection, NO inflated limits); every route merges security_headers(is_secure=<request scheme is https>) into the response headers"
desc "errors are JSON {error: str} with the pinned status; success bodies are the records below"
desc "Flask compatibility: every GET route must also accept HEAD — same status code and headers as the GET, empty body (declare each GET endpoint with methods=['GET','HEAD']); FastAPI does not auto-add HEAD"
record ErrOut {
error: str
}
record PasteOut {
id: str
title: str
type: str
created_at: str
expires_at: str | None
view: str
raw: str
download: str
}
record ViewOut {
id: str
type: str
title: str
created_at: str
expires_at: str | None
content: str | None
filename: str | None
mimetype: str | None
}
record HealthOut {
status: str
}
record IndexOut {
service: str
endpoints: list[str]
}
endpoint paste_router:
route POST /pastes body (paste_type: str, title: str, expiry: str, content: str, file: bytes) -> 201:PasteOut 400:ErrOut 413:ErrOut 429:ErrOut:
desc "multipart/form-data fields; ALL form fields have defaults so file-only uploads work without a content field (paste_type default 'text', title default '', expiry default '1d', content default '') and file is an optional UploadFile; rate limit FIRST: _limiter.allow(client IP) False -> 429 {error: 'Too many uploads. Please wait.'}; then parse_expiry(expiry), ValueError -> 400 {error: 'Invalid expiry'}; paste_type 'text': content must be non-empty after strip else 400 {error: 'Content cannot be empty'}; STORE content verbatim, never stripped (old app stripped stored content — fixed); paste_type 'image': no file -> 400 {error: 'No file selected'}; sanitize_filename, empty -> 400 same; extension must be an allowed image extension else 400 {error: 'Invalid image format'}; check_image_magic on the first 12 bytes else 400 {error: 'File content does not match image type.'}; read all bytes, len > MAX_UPLOAD_BYTES -> 413 {error: 'File too large. Maximum size is 20 MB.'}; write_upload; meta type 'image', title or original filename, mimetype derive_mimetype(ext), created_at ISO UTC, expires_at from parse_expiry; paste_type 'file': same no-file/sanitize checks; if is_text_ext: read bytes, decode utf-8 errors=replace, store as a 'text' paste WITH filename in meta; else: 20MB check, write_upload, meta type 'file', mimetype derive_mimetype(ext); any other paste_type -> 400 {error: 'Invalid paste type'}; the meta dict passed to save_meta uses EXACTLY the Paste record field names as keys (type, title, created_at, expires_at, filename, mimetype, filepath — never 'path'); success 201 PasteOut {id, title, type, created_at, expires_at, view: '/pastes/<id>', raw: '/pastes/<id>/raw', download: '/pastes/<id>/download'}"
route GET /pastes/{paste_id} -> 200:ViewOut 404:ErrOut:
desc "load_meta None -> 404 {error: 'Paste not found'}; expired -> store.delete then 404 same body; text pastes: ViewOut with content read_content or '', filename from meta (set when the paste was created from an uploaded text file, else None), mimetype None; image/file: content None, filename and mimetype from meta"
route GET /pastes/{paste_id}/download -> 200:bytes 404:ErrOut:
desc "same 404/expiry-delete handling (uploaded file path read from meta['filepath']); text -> the content utf-8 bytes as an attachment, filename meta['filename'] or 'paste.txt', media type text/plain; image/file -> the uploaded file's bytes as an attachment, filename meta['filename'], media type meta['mimetype']; uploaded file missing on disk -> 404 {error: 'Paste not found'}"
route GET /pastes/{paste_id}/raw -> 200:bytes 404:ErrOut:
desc "same 404/expiry-delete handling (uploaded file path read from meta['filepath']); text -> content utf-8 bytes, media type text/plain; charset=utf-8, no attachment; image -> uploaded file bytes, media type meta['mimetype']; file -> uploaded file bytes, media type meta['mimetype'] (old app fell through and 500'd for file pastes — fixed); uploaded file missing on disk -> 404 {error: 'Paste not found'}"
route GET /health -> 200:HealthOut:
desc "{status: 'ok'}"
route GET / -> 200:IndexOut:
desc "{service: 'paste-bin', endpoints: ['/pastes', '/health']}"
module paste_bin/app.py
glue entry
desc "app entry: create the FastAPI app and mount paste_router"
value app: FastAPI
edge api -> store : uses
edge api -> validate : uses
edge api -> ratelimit : uses
edge api -> headers : uses
edge app -> api : mounts
edge store -> validate : uses
config store_folder = "store" # directory for paste metadata + text content (env STORE_FOLDER overrides)
config upload_folder = "uploads" # directory for binary uploads (env UPLOAD_FOLDER overrides)

View File

@ -1,9 +0,0 @@
at: '2026-11-18T18:52:46+00:00'
by: owner
rounds: 0
open_questions: 0
intake_present: true
intake_filled: 0
intake_blank: 12
schema_sha: 07e1c8b9e27e76bc09f6526a9a69a84ceac6e9ff733b401d8b4f64a43f3a6f59
tests_sha: ce3bef1efa30ef8e31cd33c7fd28f9da4ee0c6768c2c3236ace0b414bc7d7c53

View File

View File

@ -1,30 +0,0 @@
{
"files": {
"__init__.py": {
"module": "",
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"test_headers.py": {
"module": "headers",
"sha256": "8aed81d422e035a12eef7131e6e5f8b112d3b3967c1e85c0895dd36e66f187f5"
},
"test_paste_api.py": {
"module": "api",
"sha256": "bc12d5fc26df3579b39752232a293ac6a6c9615a6fdecf87c685bb31b0173636"
},
"test_ratelimit.py": {
"module": "ratelimit",
"sha256": "4b260287697dee5b1d63776206455e1a9c2ffdc0b58560b3553970035c202aa1"
},
"test_store.py": {
"module": "store",
"sha256": "27a857e85d1c2fb8792046806405fe492b8fcbdf5705364e2583ef1bbec9aa5f"
},
"test_validate.py": {
"module": "validate",
"sha256": "4d94d96dc4be653dad20b640559f0ed9fbeebf54771f70c315416d69791b026c"
}
},
"hash": "780e0b7afe051aefddac938d9d47649d906fc7f4f872ec1a185fbf77c0dac637",
"version": 1
}

View File

@ -1,21 +0,0 @@
# tests for module headers (paste_bin/headers.py)
from paste_bin.headers import security_headers
def test_base_headers():
h = security_headers()
assert h["X-Content-Type-Options"] == "nosniff"
assert h["X-Frame-Options"] == "DENY"
assert h["X-XSS-Protection"] == "1; mode=block"
assert h["Referrer-Policy"] == "strict-origin-when-cross-origin"
assert h["Content-Security-Policy"] == (
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'"
)
assert "Strict-Transport-Security" not in h
def test_hsts_only_when_secure():
assert "Strict-Transport-Security" not in security_headers(is_secure=False)
h = security_headers(is_secure=True)
assert h["Strict-Transport-Security"] == "max-age=31536000; includeSubDomains"

View File

@ -1,338 +0,0 @@
# tests for module api (paste_bin/api.py)
# Owner test: at `api` verify time the app entrypoint is still a stub,
# so this mounts paste_router on its own app (no paste_bin.app import).
# The store is exercised through the router. STORE_FOLDER / UPLOAD_FOLDER
# are set only for the duration of the import (the api module builds its
# _store at import time) and restored afterwards so sibling test files
# are untouched.
import io
import os
import re
import tempfile
_TMP = tempfile.mkdtemp(prefix="paste_bin_owner_")
_prev_store = os.environ.get("STORE_FOLDER")
_prev_upload = os.environ.get("UPLOAD_FOLDER")
os.environ["STORE_FOLDER"] = os.path.join(_TMP, "store")
os.environ["UPLOAD_FOLDER"] = os.path.join(_TMP, "uploads")
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
from paste_bin.api import paste_router # noqa: E402
from paste_bin import api as api_mod # noqa: E402
from paste_bin.ratelimit import UploadRateLimiter # noqa: E402
if _prev_store is None:
del os.environ["STORE_FOLDER"]
else:
os.environ["STORE_FOLDER"] = _prev_store
if _prev_upload is None:
del os.environ["UPLOAD_FOLDER"]
else:
os.environ["UPLOAD_FOLDER"] = _prev_upload
app = FastAPI()
app.include_router(paste_router)
client = TestClient(app)
# The import-time limiter instance, captured before any fixture can swap it —
# used to assert the module-level construction contract (10/60, no inflation).
_IMPORT_TIME_LIMITER = api_mod._limiter
import pytest # noqa: E402
@pytest.fixture(autouse=True)
def _fresh_limiter_per_test():
# every POST to /pastes consumes a rate slot (the limiter runs first,
# even on requests that later 400). The suite makes more than 10 posts,
# so each test gets a fresh 10/60 limiter; the module-level instance is
# restored afterwards.
orig = api_mod._limiter
api_mod._limiter = UploadRateLimiter(max_attempts=10, window_seconds=60)
yield
api_mod._limiter = orig
PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 16
WEBP_BYTES = b"RIFF\x00\x00\x00\x00WEBP" + b"\x00" * 8
AVI_RIFF_BYTES = b"RIFF\x00\x00\x00\x00AVI " + b"\x00" * 8
def _post_text(content, title="t", expiry="1d"):
return client.post(
"/pastes",
data={"paste_type": "text", "title": title, "expiry": expiry, "content": content},
)
def _post_file(fname, data, paste_type, title="t", expiry="1d"):
return client.post(
"/pastes",
data={"paste_type": paste_type, "title": title, "expiry": expiry},
files={"file": (fname, io.BytesIO(data), "application/octet-stream")},
)
def _create_ok(r):
assert r.status_code == 201, r.text
return r.json()
# --- basic routes ---------------------------------------------------------
def test_routes_registered():
paths = app.openapi()["paths"]
assert "/pastes" in paths
assert "/pastes/{paste_id}" in paths
assert "/pastes/{paste_id}/raw" in paths
assert "/pastes/{paste_id}/download" in paths
assert "/health" in paths
assert "/" in paths
def test_index():
r = client.get("/")
assert r.status_code == 200
body = r.json()
assert body["service"] == "paste-bin"
assert "/pastes" in body["endpoints"]
assert "/health" in body["endpoints"]
def test_health():
r = client.get("/health")
assert r.status_code == 200
assert r.json() == {"status": "ok"}
def test_security_headers_present():
r = client.get("/health")
assert r.headers.get("X-Content-Type-Options") == "nosniff"
assert r.headers.get("X-Frame-Options") == "DENY"
assert r.headers.get("X-XSS-Protection") == "1; mode=block"
assert r.headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"
assert "Content-Security-Policy" in r.headers
def test_module_limiter_uses_class_defaults():
# the IMPORT-TIME module-level limiter must be the pinned 10/60 contract —
# no config indirection, no inflated limits (the per-test fixture swaps
# api_mod._limiter, so assert on the captured import-time instance)
assert _IMPORT_TIME_LIMITER.max_attempts == 10
assert _IMPORT_TIME_LIMITER.window_seconds == 60
def test_head_supported_on_get_routes():
# Flask auto-added HEAD to GET routes; the port must keep that ability
# (FastAPI does not — 405 without explicit methods=['GET', 'HEAD'])
r = client.request("HEAD", "/health")
assert r.status_code == 200
assert r.content == b""
r = client.request("HEAD", "/pastes/ffffffffffffffff")
assert r.status_code == 404
# --- text pastes ----------------------------------------------------------
def test_text_paste_roundtrip():
r = _post_text("hello world", title="hi")
body = _create_ok(r)
pid = body["id"]
assert re.fullmatch(r"[a-f0-9]{16}", pid)
assert body["type"] == "text"
assert body["title"] == "hi"
assert body["view"] == f"/pastes/{pid}"
assert body["raw"] == f"/pastes/{pid}/raw"
assert body["download"] == f"/pastes/{pid}/download"
assert body["expires_at"] is not None
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
vb = v.json()
assert vb["type"] == "text"
assert vb["content"] == "hello world"
assert vb["filename"] is None
assert vb["mimetype"] is None
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == b"hello world"
assert raw.headers["content-type"].startswith("text/plain")
dl = client.get(f"/pastes/{pid}/download")
assert dl.status_code == 200
assert dl.content == b"hello world"
assert "attachment" in dl.headers.get("content-disposition", "")
def test_text_content_stored_verbatim():
payload = " leading spaces\n\ntrailing newline\n"
body = _create_ok(_post_text(payload))
raw = client.get(f"/pastes/{body['id']}/raw")
assert raw.status_code == 200
assert raw.content == payload.encode("utf-8")
def test_empty_content_400():
r = _post_text(" \n ")
assert r.status_code == 400
assert r.json()["error"] == "Content cannot be empty"
def test_invalid_expiry_400():
r = _post_text("x", expiry="2 weeks")
assert r.status_code == 400
assert r.json()["error"] == "Invalid expiry"
def test_invalid_paste_type_400():
r = client.post(
"/pastes",
data={"paste_type": "video", "title": "x", "expiry": "1d", "content": "c"},
)
assert r.status_code == 400
assert r.json()["error"] == "Invalid paste type"
def test_forever_paste_has_no_expiry():
body = _create_ok(_post_text("keep", expiry="forever"))
assert body["expires_at"] is None
v = client.get(f"/pastes/{body['id']}")
assert v.status_code == 200
assert v.json()["expires_at"] is None
# --- ids ------------------------------------------------------------------
def test_unknown_paste_id_404():
r = client.get("/pastes/" + "z" * 16)
assert r.status_code == 404
assert r.json()["error"] == "Paste not found"
def test_malformed_ids_404():
assert client.get("/pastes/abc").status_code == 404 # too short
assert client.get("/pastes/" + "g" * 16).status_code == 404 # not hex
def test_expired_paste_404_and_deleted():
body = _create_ok(_post_text("doomed", expiry="1h"))
pid = body["id"]
# whitebox: force the expiry into the past
meta = api_mod._store.load_meta(pid)
meta["expires_at"] = "2020-01-01T00:00:00+00:00"
api_mod._store.save_meta(pid, meta)
r = client.get(f"/pastes/{pid}")
assert r.status_code == 404
assert r.json()["error"] == "Paste not found"
assert api_mod._store.load_meta(pid) is None # deleted on view
# --- image uploads ---------------------------------------------------------
def test_svg_upload_rejected():
r = _post_file("evil.svg", b"<svg></svg>", "image")
assert r.status_code == 400
assert r.json()["error"] == "Invalid image format"
def test_fake_image_magic_rejected():
r = _post_file("fake.png", b"not a png at all", "image")
assert r.status_code == 400
assert r.json()["error"] == "File content does not match image type."
def test_riff_avi_rejected_as_webp():
# old bug: any RIFF container passed the webp check
r = _post_file("clip.webp", AVI_RIFF_BYTES, "image")
assert r.status_code == 400
assert r.json()["error"] == "File content does not match image type."
def test_valid_webp_accepted():
body = _create_ok(_post_file("anim.webp", WEBP_BYTES, "image"))
assert body["type"] == "image"
def test_image_paste_roundtrip():
body = _create_ok(_post_file("pic.png", PNG_BYTES, "image", title="pic"))
pid = body["id"]
assert body["type"] == "image"
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
vb = v.json()
assert vb["filename"] == "pic.png"
assert vb["mimetype"] == "image/png"
assert vb["content"] is None
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == PNG_BYTES
assert raw.headers["content-type"].split(";")[0].strip() == "image/png"
def test_no_file_for_image_400():
r = client.post("/pastes", data={"paste_type": "image", "title": "x", "expiry": "1d"})
assert r.status_code == 400
assert r.json()["error"] == "No file selected"
def test_empty_filename_400():
r = _post_file("...", b"x", "image")
assert r.status_code == 400
assert r.json()["error"] == "No file selected"
# --- file uploads -----------------------------------------------------------
def test_text_file_upload_stored_as_text():
code = "print('hi')\n"
body = _create_ok(_post_file("hello.py", code.encode(), "file"))
assert body["type"] == "text"
pid = body["id"]
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
vb = v.json()
assert vb["content"] == code
assert vb["filename"] == "hello.py"
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == code.encode()
def test_binary_file_upload_roundtrip():
data = bytes(range(256)) * 4
body = _create_ok(_post_file("blob.bin", data, "file"))
assert body["type"] == "file"
pid = body["id"]
v = client.get(f"/pastes/{pid}")
assert v.status_code == 200
assert v.json()["mimetype"] == "application/octet-stream"
# raw on a file-type paste (old bug: fell through to 500)
raw = client.get(f"/pastes/{pid}/raw")
assert raw.status_code == 200
assert raw.content == data
def test_upload_too_large_413():
big = b"A" * (20 * 1024 * 1024 + 1)
r = _post_file("big.bin", big, "file")
assert r.status_code == 413
assert r.json()["error"] == "File too large. Maximum size is 20 MB."
# --- rate limiting (must run last: resets the shared limiter) ---------------
def test_rate_limit_11th_upload_429():
# the autouse fixture provides a fresh 10/60 limiter for this test
for i in range(10):
r = _post_text(f"rl {i}", title=f"rl{i}")
assert r.status_code == 201, r.text
r = _post_text("rl 11", title="rl11")
assert r.status_code == 429
assert r.json()["error"] == "Too many uploads. Please wait."

View File

@ -1,42 +0,0 @@
# tests for module ratelimit (paste_bin/ratelimit.py)
import time
from paste_bin.ratelimit import UploadRateLimiter
def test_allows_up_to_max_then_blocks():
lim = UploadRateLimiter(max_attempts=3, window_seconds=60)
assert lim.allow("1.2.3.4") is True
assert lim.allow("1.2.3.4") is True
assert lim.allow("1.2.3.4") is True
assert lim.allow("1.2.3.4") is False
def test_other_ips_are_independent():
lim = UploadRateLimiter(max_attempts=2, window_seconds=60)
assert lim.allow("a") is True
assert lim.allow("a") is True
assert lim.allow("a") is False
assert lim.allow("b") is True
def test_window_slides():
lim = UploadRateLimiter(max_attempts=2, window_seconds=1)
assert lim.allow("x") is True
assert lim.allow("x") is True
assert lim.allow("x") is False
time.sleep(1.1)
assert lim.allow("x") is True
def test_stale_keys_pruned():
lim = UploadRateLimiter(max_attempts=10, window_seconds=1)
for _ in range(3):
lim.allow("ghost")
time.sleep(1.1)
assert "ghost" in lim.attempts # still present until a call prunes
lim.allow("live")
# old bug: one list per ip leaked forever — stale keys must be dropped
assert "ghost" not in lim.attempts
assert "live" in lim.attempts

View File

@ -1,123 +0,0 @@
# tests for module store (paste_bin/store.py)
import os
from paste_bin.store import PasteStore
def _make(tmp_path):
return PasteStore(str(tmp_path / "store"), str(tmp_path / "uploads"))
def test_store_uses_validate_id_checker():
# the store must import validate's is_valid_paste_id — never a
# locally redefined shadow copy
import paste_bin.store as store_mod
from paste_bin import validate
assert store_mod.is_valid_paste_id is validate.is_valid_paste_id
def _text_meta(title="t", expires_at=None):
return {
"type": "text",
"title": title,
"created_at": "2026-01-01T00:00:00+00:00",
"expires_at": expires_at,
"filename": None,
"mimetype": None,
"filepath": None,
}
def test_ctor_creates_dirs(tmp_path):
_make(tmp_path)
assert (tmp_path / "store").is_dir()
assert (tmp_path / "uploads").is_dir()
def test_meta_roundtrip(tmp_path):
s = _make(tmp_path)
s.save_meta("a" * 16, _text_meta("hello"))
assert s.load_meta("a" * 16)["title"] == "hello"
assert s.load_meta("b" * 16) is None # missing
assert s.load_meta("../etc/passwd") is None # invalid id
# corrupt JSON -> None, never raises
bad = "c" * 16
s.save_meta(bad, _text_meta())
(tmp_path / "store" / bad).write_text("{not json", encoding="utf-8")
assert s.load_meta(bad) is None
def test_content_written_verbatim(tmp_path):
s = _make(tmp_path)
payload = " leading spaces\n\ntrailing newline\n"
s.write_content("d" * 16, payload)
assert s.read_content("d" * 16) == payload # no stripping
assert s.read_content("e" * 16) is None
def test_write_upload_returns_absolute_path(tmp_path):
s = _make(tmp_path)
path = s.write_upload("f" * 16, b"\x00\x01binary", "bin")
assert os.path.isabs(path)
with open(path, "rb") as f:
assert f.read() == b"\x00\x01binary"
assert (tmp_path / "uploads" / ("f" * 16 + ".bin")).is_file()
def test_save_meta_leaves_no_tmp_files(tmp_path):
s = _make(tmp_path)
s.save_meta("1" * 16, _text_meta())
leftovers = [p.name for p in (tmp_path / "store").iterdir() if ".tmp." in p.name]
assert leftovers == []
def test_delete_removes_meta_content_and_upload(tmp_path):
s = _make(tmp_path)
pid = "2" * 16
meta = {
"type": "image",
"title": "i",
"created_at": "2026-01-01T00:00:00+00:00",
"expires_at": None,
"filename": "x.png",
"mimetype": "image/png",
"filepath": None,
}
s.save_meta(pid, meta)
s.write_content(pid, "stray")
path = s.write_upload(pid, b"\x89PNG", "png")
meta["filepath"] = path
s.delete(pid)
assert not (tmp_path / "store" / pid).exists()
assert not (tmp_path / "store" / (pid + ".txt")).exists()
assert not os.path.exists(path)
def test_is_expired(tmp_path):
s = _make(tmp_path)
assert s.is_expired({"expires_at": None}) is False
assert s.is_expired({"expires_at": "2020-01-01T00:00:00+00:00"}) is True
assert s.is_expired({"expires_at": "2999-01-01T00:00:00+00:00"}) is False
def test_cleanup_expired_deletes_only_expired_and_stale_tmp(tmp_path):
s = _make(tmp_path)
pid_expired = "3" * 16
pid_fresh = "4" * 16
s.save_meta(pid_expired, _text_meta("old", "2020-01-01T00:00:00+00:00"))
s.write_content(pid_expired, "gone soon")
s.save_meta(pid_fresh, _text_meta("new", "2999-01-01T00:00:00+00:00"))
s.write_content(pid_fresh, "keep")
# stale tmp file left by a crashed write (old app never cleaned these)
stale = tmp_path / "store" / ("5" * 16 + ".tmp.12345")
stale.write_text("{}", encoding="utf-8")
n = s.cleanup_expired()
assert n == 1
assert s.load_meta(pid_expired) is None
assert not (tmp_path / "store" / (pid_expired + ".txt")).exists()
assert s.load_meta(pid_fresh) is not None
assert (tmp_path / "store" / (pid_fresh + ".txt")).is_file()
assert not stale.exists()

View File

@ -1,106 +0,0 @@
# tests for module validate (paste_bin/validate.py)
import datetime
import re
import pytest
from paste_bin import validate
def test_generate_paste_id_shape_and_uniqueness():
a = validate.generate_paste_id()
b = validate.generate_paste_id()
assert re.fullmatch(r"[a-f0-9]{16}", a)
assert re.fullmatch(r"[a-f0-9]{16}", b)
assert a != b
def test_is_valid_paste_id():
assert validate.is_valid_paste_id("0123456789abcdef") is True
assert validate.is_valid_paste_id("a" * 16) is True
assert validate.is_valid_paste_id("0123456789abcde") is False # 15 chars
assert validate.is_valid_paste_id("0123456789abcdef0") is False # 17 chars
assert validate.is_valid_paste_id("0123456789ABCDEF") is False # uppercase
assert validate.is_valid_paste_id("../etc/passwd") is False
assert validate.is_valid_paste_id("") is False
def test_sanitize_filename():
assert validate.sanitize_filename("../../etc/passwd") == "passwd"
assert validate.sanitize_filename("/a/b/my file.txt") == "my_file.txt"
assert validate.sanitize_filename("???") == "___"
assert validate.sanitize_filename("...") == ""
assert len(validate.sanitize_filename("a" * 300)) <= 255
assert not validate.sanitize_filename("..hidden.txt").startswith(".")
def test_parse_expiry_known_keys():
now = datetime.datetime.now(datetime.timezone.utc)
for key, hours in [("1h", 1), ("1d", 24), ("1w", 24 * 7), ("1m", 24 * 30)]:
ts = datetime.datetime.fromisoformat(validate.parse_expiry(key))
delta = (ts - now).total_seconds()
assert abs(delta - hours * 3600) < 120
def test_parse_expiry_forever_is_none():
assert validate.parse_expiry("forever") is None
def test_parse_expiry_unknown_key_raises():
# old app silently defaulted unknown keys to 1 day — must now reject
with pytest.raises(ValueError):
validate.parse_expiry("2 weeks")
with pytest.raises(ValueError):
validate.parse_expiry("")
def _png() -> bytes:
return b"\x89PNG\r\n\x1a\n" + b"\x00" * 16
def _riff(kind: bytes) -> bytes:
# RIFF container: 0..3 'RIFF', 4..7 size, 8..11 type tag
return b"RIFF" + b"\x00\x00\x00\x00" + kind + b"\x00" * 8
def test_check_image_magic():
assert validate.check_image_magic(_png(), "png") is True
assert validate.check_image_magic(b"\xff\xd8\xff" + b"0" * 10, "jpg") is True
assert validate.check_image_magic(b"GIF87a" + b"0" * 10, "gif") is True
assert validate.check_image_magic(b"GIF89a" + b"0" * 10, "gif") is True
assert validate.check_image_magic(b"BM" + b"0" * 10, "bmp") is True
assert validate.check_image_magic(b"II*\x00" + b"0" * 10, "tiff") is True
# webp needs the WEBP tag at offset 8, not just any RIFF
assert validate.check_image_magic(_riff(b"WEBP"), "webp") is True
# RIFF+AVI must be rejected (old bug: accepted any RIFF as webp)
assert validate.check_image_magic(_riff(b"AVI "), "webp") is False
# magic must match the requested extension
assert validate.check_image_magic(_png(), "jpg") is False
assert validate.check_image_magic(_png(), "txt") is False
def test_derive_mimetype():
assert validate.derive_mimetype("png") == "image/png"
assert validate.derive_mimetype("jpg") == "image/jpeg"
assert validate.derive_mimetype("jpeg") == "image/jpeg"
assert validate.derive_mimetype("gif") == "image/gif"
assert validate.derive_mimetype("bmp") == "image/bmp"
assert validate.derive_mimetype("webp") == "image/webp"
assert validate.derive_mimetype("tiff") == "image/tiff"
assert validate.derive_mimetype("txt") == "application/octet-stream"
assert validate.derive_mimetype("bin") == "application/octet-stream"
def test_is_image_ext():
assert validate.is_image_ext("photo.png") is True
assert validate.is_image_ext("PHOTO.PNG") is True
assert validate.is_image_ext("photo.pngx") is False
assert validate.is_image_ext("noext") is False
def test_is_text_ext():
assert validate.is_text_ext("script.py") is True
assert validate.is_text_ext("notes.md") is True
assert validate.is_text_ext("photo.png") is False
assert validate.is_text_ext("noext") is False

View File

@ -1,25 +0,0 @@
{
admin off
}
:18901 {
root * .
# every path the OpenAPI doc declares is reachable same-origin:
# GET / -> JSON index (API)
# GET /health -> {status:ok} (API)
# GET/POST /pastes* -> view/raw/dl/create (API)
# /openapi.json -> contract doc (served next to the client)
# the SPA itself lives at /index.html (+ /client.js /styles.css /app.js)
handle /pastes* {
reverse_proxy 127.0.0.1:18900
}
handle /health {
reverse_proxy 127.0.0.1:18900
}
@apiroot path /
handle @apiroot {
reverse_proxy 127.0.0.1:18900
}
file_server
}

500
ui/app.js
View File

@ -1,500 +0,0 @@
// paste-bin UI — app logic.
// Contract surface is ONLY window.PasteBinAPI (generated client.js from openapi.json).
// No hand-rolled fetch, no hardcoded endpoints: every call below is a generated op.
"use strict";
(() => {
const API = window.PasteBinAPI;
if (!API) {
document.body.insertAdjacentHTML(
"afterbegin",
'<div style="padding:20px;background:#e94560;color:#fff;font-family:monospace">client.js failed to load — regenerate: archllm openapi paste-bin --client --out ui</div>'
);
return;
}
const $ = (s) => document.querySelector(s);
// pinned contract literals (mirror of x-error-literals, used for early client-side feedback)
const ERR_EMPTY_CONTENT = "Content cannot be empty";
const ERR_NO_FILE = "No file selected";
const ERR_MISMATCH = "File content does not match image type.";
const ERR_TOO_LARGE = "File too large. Maximum size is 20 MB.";
const ERR_NOT_FOUND = "Paste not found";
const MAX_BYTES = 20 * 1024 * 1024;
const IMG_ACCEPT = "image/png,image/jpeg,image/gif,image/bmp,image/webp,image/svg+xml,image/tiff";
const TYPE_ICON = { text: "📝", image: "🖼", file: "📄" };
const state = { type: "text", file: null, lastView: null, lastId: null };
const recent = loadRecent();
/* ---------------- toasts ---------------- */
function toast(kind, title, detail = "", ttl = 5200) {
const el = document.createElement("div");
el.className = `toast toast-${kind}`;
const t = document.createElement("div");
t.className = "toast-title";
t.textContent = title;
el.appendChild(t);
if (detail) {
const d = document.createElement("div");
d.className = "toast-detail";
d.textContent = detail;
el.appendChild(d);
}
const x = document.createElement("button");
x.className = "toast-x";
x.setAttribute("aria-label", "Dismiss");
x.textContent = "×";
x.onclick = () => el.remove();
el.appendChild(x);
$("#toasts").appendChild(el);
requestAnimationFrame(() => el.classList.add("in"));
setTimeout(() => {
el.classList.remove("in");
setTimeout(() => el.remove(), 300);
}, ttl);
}
function errToast(e) {
const kind = e && e.status === 429 ? "warn" : "err";
const hint =
e && e.status === 429
? "upload budget (10/min) resets within 60 s"
: e && e.apiError
? `pinned contract message · ${API.ERROR_MESSAGES ? "see openapi.json x-error-literals" : ""}`
: "network error — is the API proxy up?";
toast(kind, e && e.message ? e.message : String(e), hint);
}
/* ---------------- health + contract badges ---------------- */
async function pingHealth() {
const pill = $("#healthPill");
try {
await API.getHealth();
pill.className = "pill pill-ok";
pill.innerHTML = '<span class="dot"></span>api ok';
} catch {
pill.className = "pill pill-err";
pill.innerHTML = '<span class="dot"></span>api down';
}
}
async function loadBadges() {
try {
const [idx, doc] = await Promise.all([API.getIndex(), API.fetchContract()]);
$("#brandTag").textContent = `service ${idx.service} · spec → openapi → client → ui`;
const ops = Object.values(doc.paths).reduce(
(n, p) => n + Object.keys(p).filter((m) => /^(get|post|put|delete|patch)$/.test(m)).length,
0
);
const b = $("#contractBadge");
b.textContent = `v${doc.info.version} · ${ops} ops`;
b.title = `OpenAPI ${doc.openapi} — ${doc.info.title} (openapi.json)`;
} catch {
$("#contractBadge").textContent = "v?";
}
}
/* ---------------- create: type tabs ---------------- */
function setType(t) {
state.type = t;
for (const b of $("#typeSeg").children) {
const on = b.dataset.t === t;
b.classList.toggle("on", on);
b.setAttribute("aria-selected", on ? "true" : "false");
}
$("#paneText").hidden = t !== "text";
$("#paneFile").hidden = t === "text";
$("#fileInput").accept = t === "image" ? IMG_ACCEPT : "";
$("#dzSub").textContent =
t === "image"
? "png · jpeg · gif · bmp · webp · svg · tiff — max 20 MB"
: "any file — max 20 MB";
if (state.file) validateFileForType();
}
$("#typeSeg").addEventListener("click", (e) => {
const b = e.target.closest("button[data-t]");
if (b) setType(b.dataset.t);
});
/* ---------------- create: file handling ---------------- */
const fileInput = $("#fileInput");
const dz = $("#dropzone");
function fmtSize(bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
return (bytes / (1024 * 1024)).toFixed(2) + " MB";
}
function validateFileForType() {
if (!state.file) return true;
if (state.type === "image" && !state.file.type.startsWith("image/")) {
toast("err", ERR_MISMATCH, state.file.name + " — switch to File tab for non-images");
return false;
}
return true;
}
function setFile(f) {
if (!f) return;
state.file = f;
if (f.size > MAX_BYTES) toast("warn", ERR_TOO_LARGE, f.name + " is " + fmtSize(f.size));
if (!validateFileForType()) {
clearFile();
return;
}
const isImg = state.type === "image" && f.type.startsWith("image/");
$("#dzIdle").hidden = true;
$("#dzPreview").hidden = false;
const thumb = $("#dzThumb");
const ico = $("#dzFileIco");
if (isImg) {
thumb.src = URL.createObjectURL(f);
thumb.hidden = false;
ico.hidden = true;
} else {
thumb.hidden = true;
thumb.removeAttribute("src");
ico.hidden = false;
ico.textContent = state.type === "file" ? "📄" : "❓";
}
$("#dzName").textContent = f.name;
$("#dzMeta").textContent = `${fmtSize(f.size)} · ${f.type || "unknown type"}`;
}
function clearFile() {
state.file = null;
fileInput.value = "";
const thumb = $("#dzThumb");
thumb.hidden = true;
thumb.removeAttribute("src");
$("#dzIdle").hidden = false;
$("#dzPreview").hidden = true;
}
dz.addEventListener("click", (e) => {
if (e.target.closest("#dzRemove")) return;
fileInput.click();
});
dz.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
fileInput.click();
}
});
fileInput.addEventListener("change", () => setFile(fileInput.files[0] || null));
$("#dzRemove").addEventListener("click", (e) => {
e.stopPropagation();
clearFile();
});
["dragenter", "dragover"].forEach((ev) =>
dz.addEventListener(ev, (e) => {
e.preventDefault();
dz.classList.add("dragover");
})
);
["dragleave", "drop"].forEach((ev) =>
dz.addEventListener(ev, (e) => {
e.preventDefault();
dz.classList.remove("dragover");
})
);
dz.addEventListener("drop", (e) => {
const f = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
if (f) setFile(f);
});
/* ---------------- create: submit ---------------- */
$("#content").addEventListener("input", () => {
$("#charCount").textContent = String($("#content").value.length);
});
async function createPaste() {
const btn = $("#createBtn");
const title = $("#title").value.trim();
const expiry = $("#expiry").value;
const content = $("#content").value;
if (state.type === "text" && !content.trim()) {
toast("err", ERR_EMPTY_CONTENT);
$("#content").focus();
return;
}
if (state.type !== "text" && !state.file) {
toast("err", ERR_NO_FILE);
return;
}
if (state.file && state.file.size > MAX_BYTES) {
toast("warn", ERR_TOO_LARGE, state.file.name + " is " + fmtSize(state.file.size));
return;
}
btn.disabled = true;
btn.textContent = "Creating…";
$("#createHint").textContent = `POST /pastes · ${state.type} · ${expiry}`;
try {
const out = await API.postPastes({
paste_type: state.type,
title,
expiry,
content: state.type === "text" ? content : "",
file: state.type === "text" ? null : state.file,
});
toast("ok", `Created ${out.id}`, out.title ? `"${out.title}"` : state.type + " paste");
remember(out);
// reset the form, keep the type
$("#title").value = "";
$("#content").value = "";
$("#charCount").textContent = "0";
clearFile();
openPaste(out.id);
} catch (e) {
errToast(e);
} finally {
btn.disabled = false;
btn.textContent = "Create paste";
$("#createHint").textContent = "";
}
}
$("#createBtn").addEventListener("click", createPaste);
/* ---------------- view ---------------- */
function fmtTime(iso) {
if (!iso) return "";
const d = new Date(iso);
return isNaN(d) ? iso : d.toLocaleString();
}
function showOpenErr(msg) {
const el = $("#openErr");
el.textContent = msg;
el.hidden = !msg;
}
async function openPaste(id) {
id = (id || "").trim();
if (!API.PASTE_ID_RE.test(id)) {
showOpenErr("id must be 16 hex chars (contract: paste_id pattern)");
return;
}
showOpenErr("");
$("#openId").value = id;
$("#stage").innerHTML =
'<div class="stage-loading"><span class="spinner"></span>loading ' + id + "…</div>";
$("#viewMeta").hidden = true;
$("#viewActions").hidden = true;
try {
const v = await API.getPastesPaste_id(id);
state.lastView = v;
state.lastId = id;
renderView(v);
} catch (e) {
state.lastView = null;
state.lastId = null;
renderViewError(e);
}
}
function renderView(v) {
const stage = $("#stage");
stage.innerHTML = "";
if (v.type === "text") {
const pre = document.createElement("pre");
pre.className = "view-text";
pre.textContent = v.content == null ? "" : v.content;
stage.appendChild(pre);
} else if (v.type === "image") {
const wrap = document.createElement("div");
wrap.className = "stage-img";
const img = document.createElement("img");
img.alt = v.title || "paste image";
img.src = API.getPastesPaste_idRawUrl(v.id);
img.onerror = () => {
img.onerror = null;
renderViewError(new API.ApiError(0, "image failed to load"));
};
wrap.appendChild(img);
stage.appendChild(wrap);
} else {
const wrap = document.createElement("div");
wrap.className = "view-file";
wrap.innerHTML =
'<div class="view-file-ico" aria-hidden="true">📄</div>' +
'<div class="view-file-name"></div>' +
'<div class="view-file-sub"></div>';
wrap.querySelector(".view-file-name").textContent = v.filename || "unnamed file";
wrap.querySelector(".view-file-sub").textContent = v.mimetype || "unknown type";
stage.appendChild(wrap);
}
const bits = [];
bits.push("<b>type</b> " + v.type);
if (v.title) bits.push("<b>title</b> " + escapeHtml(v.title));
if (v.filename) bits.push("<b>file</b> " + escapeHtml(v.filename));
if (v.mimetype) bits.push("<b>mime</b> " + v.mimetype);
bits.push("<b>created</b> " + fmtTime(v.created_at));
bits.push(v.expires_at ? "<b>expires</b> " + fmtTime(v.expires_at) : "<b>expires</b> never");
const meta = $("#viewMeta");
meta.innerHTML = bits.join(" · ");
meta.hidden = false;
$("#actRaw").href = API.getPastesPaste_idRawUrl(v.id);
$("#actDownload").href = API.getPastesPaste_idDownloadUrl(v.id);
$("#viewActions").hidden = false;
}
function renderViewError(e) {
const notFound = e && e.status === 404;
$("#stage").innerHTML = "";
const wrap = document.createElement("div");
wrap.className = "view-error";
wrap.innerHTML =
'<div class="view-error-ico" aria-hidden="true">' + (notFound ? "🔍" : "⚠️") + "</div>" +
'<div class="view-error-title"></div>' +
'<div class="view-error-sub"></div>';
wrap.querySelector(".view-error-title").textContent = notFound
? ERR_NOT_FOUND
: (e && e.message) || "could not load";
wrap.querySelector(".view-error-sub").textContent = notFound
? "it expired, or the id is wrong"
: "check the health pill — is the API up?";
$("#stage").appendChild(wrap);
$("#viewMeta").hidden = true;
$("#viewActions").hidden = true;
}
function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => ({
"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
}[c]));
}
$("#openBtn").addEventListener("click", () => openPaste($("#openId").value));
$("#openId").addEventListener("keydown", (e) => {
if (e.key === "Enter") openPaste($("#openId").value);
});
/* ---------------- view: actions ---------------- */
async function copyText(text, label) {
try {
await navigator.clipboard.writeText(text);
toast("ok", "Copied " + label);
} catch {
// fallback for non-secure contexts
const ta = document.createElement("textarea");
ta.value = text;
ta.style.position = "fixed";
ta.style.opacity = "0";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
toast("ok", "Copied " + label);
} catch {
toast("err", "Clipboard blocked", "select & copy manually");
}
ta.remove();
}
}
$("#actCopyJson").addEventListener("click", () => {
if (state.lastView) copyText(JSON.stringify(state.lastView, null, 2), "JSON");
});
$("#actCopyId").addEventListener("click", () => {
if (state.lastId) copyText(state.lastId, "id");
});
/* ---------------- recent chips (localStorage — the API has no list endpoint) ---------------- */
function loadRecent() {
try {
const raw = localStorage.getItem("pb.recent");
const arr = raw ? JSON.parse(raw) : [];
return Array.isArray(arr) ? arr : [];
} catch {
return [];
}
}
function saveRecent(list) {
try {
localStorage.setItem("pb.recent", JSON.stringify(list));
} catch {
/* private mode — chips just won't persist */
}
}
function remember(out) {
const list = loadRecent().filter((r) => r.id !== out.id);
list.unshift({ id: out.id, title: out.title, type: out.type, created_at: out.created_at });
saveRecent(list.slice(0, 12));
renderChips();
}
function renderChips() {
const list = loadRecent();
const box = $("#chips");
box.innerHTML = "";
$("#recentClear").hidden = list.length === 0;
if (!list.length) {
const s = document.createElement("span");
s.className = "chips-empty";
s.textContent = "nothing yet — pastes you create land here";
box.appendChild(s);
return;
}
for (const r of list) {
const chip = document.createElement("div");
chip.className = "chip";
chip.title = r.id + (r.title ? " — " + r.title : "") + (r.created_at ? " · " + fmtTime(r.created_at) : "");
const ico = document.createElement("span");
ico.className = "chip-ico";
ico.textContent = TYPE_ICON[r.type] || "📄";
const id = document.createElement("span");
id.className = "chip-id";
id.textContent = r.id;
chip.appendChild(ico);
chip.appendChild(id);
if (r.title) {
const t = document.createElement("span");
t.className = "chip-title";
t.textContent = r.title;
chip.appendChild(t);
}
const x = document.createElement("button");
x.className = "chip-x";
x.setAttribute("aria-label", "Remove from recent");
x.textContent = "×";
x.onclick = (e) => {
e.stopPropagation();
saveRecent(loadRecent().filter((q) => q.id !== r.id));
renderChips();
};
chip.appendChild(x);
chip.addEventListener("click", () => openPaste(r.id));
box.appendChild(chip);
}
}
$("#recentClear").addEventListener("click", () => {
saveRecent([]);
renderChips();
});
/* ---------------- boot ---------------- */
setType("text");
renderChips();
pingHealth();
setInterval(pingHealth, 30000);
loadBadges();
})();

View File

@ -1,100 +0,0 @@
// AUTO-GENERATED — do not edit by hand.
// source: openapi v1.0.0 (title: paste_bin)
// generator: archllm contract emission (pure function of the OpenAPI document)
// regenerate: archllm openapi <target> --client
"use strict";
(() => {
const API = { title: "paste_bin", version: "1.0.0", base: '' };
// pinned error literals (x-error-literals — exact strings from the signed spec)
const ERROR_MESSAGES = {
"POST /pastes": {
400: ["Content cannot be empty", "File content does not match image type.", "Invalid expiry", "Invalid image format", "Invalid paste type", "No file selected"],
413: ["File too large. Maximum size is 20 MB."],
429: ["Too many uploads. Please wait."],
},
"GET /pastes/{paste_id}": {
404: ["Paste not found"],
},
"GET /pastes/{paste_id}/download": {
404: ["Paste not found"],
},
"GET /pastes/{paste_id}/raw": {
404: ["Paste not found"],
},
};
// path-parameter patterns (from the contract)
const PASTE_ID_RE = /^[a-f0-9]{16}$/;
class ApiError extends Error {
constructor(status, message) { super(`[${status}] ${message}`); this.status = status; this.apiError = true; }
}
async function _req(method, path, body) {
const opts = { method };
if (body) opts.body = body;
const r = await fetch(API.base + path, opts);
const ct = r.headers.get("content-type") || "";
const data = ct.includes("application/json") ? await r.json() : null;
if (!r.ok) throw new ApiError(r.status, (data && data.error) || r.statusText);
return data;
}
const enc = encodeURIComponent;
// response/request shapes (components.schemas)
/** @typedef { type: string, title: string, created_at: string, expires_at: string | null, filename: string | null, mimetype: string | null, filepath: string | null } Paste */
/** @typedef { error: string } ErrOut */
/** @typedef { id: string, title: string, type: string, created_at: string, expires_at: string | null, view: string, raw: string, download: string } PasteOut */
/** @typedef { id: string, type: string, title: string, created_at: string, expires_at: string | null, content: string | null, filename: string | null, mimetype: string | null } ViewOut */
/** @typedef { status: string } HealthOut */
/** @typedef { service: string, endpoints: any[] } IndexOut */
// POST /pastes — multipart/form-data fields; ALL form fields have defaults so file-only uploads work withou
async function postPastes({paste_type = "text", title = "", expiry = "1d", content = "", file = null} = {}) {
const fd = new FormData();
fd.append("paste_type", paste_type);
fd.append("title", title);
fd.append("expiry", expiry);
fd.append("content", content);
if (file) fd.append("file", file);
return _req("POST", `/pastes`, fd);
}
// GET /pastes/{paste_id} — load_meta None -> 404 {error: 'Paste not found'}; expired -> store.delete then 404 same bo
async function getPastesPaste_id(paste_id) {
return _req("GET", `/pastes/${enc(paste_id)}`);
}
// GET /pastes/{paste_id}/download — same 404/expiry-delete handling (uploaded file path read from meta['filepath']); text -> t
function getPastesPaste_idDownloadUrl(paste_id) {
return API.base + `/pastes/${enc(paste_id)}/download`;
}
// GET /pastes/{paste_id}/raw — same 404/expiry-delete handling (uploaded file path read from meta['filepath']); text -> c
function getPastesPaste_idRawUrl(paste_id) {
return API.base + `/pastes/${enc(paste_id)}/raw`;
}
// GET /health — {status: 'ok'}
async function getHealth() {
return _req("GET", `/health`);
}
// GET / — {service: 'paste-bin', endpoints: ['/pastes', '/health']}
async function getIndex() {
return _req("GET", `/`);
}
// the OpenAPI document itself (serve it next to this client)
async function fetchContract() {
const r = await fetch(API.base + "/openapi.json");
return r.json();
}
window.PasteBinAPI = Object.freeze({
API, ERROR_MESSAGES, ApiError,
PASTE_ID_RE,
_req, postPastes, getPastesPaste_id, getPastesPaste_idDownloadUrl, getPastesPaste_idRawUrl, getHealth, getIndex, fetchContract,
});
})();

View File

@ -1,138 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>paste-bin</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📋%3C/text%3E%3C/svg%3E">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<header class="topbar">
<div class="topbar-inner">
<div class="brand">
<span class="brand-mark" aria-hidden="true">📋</span>
<span class="brand-name">paste<span class="accent">-bin</span></span>
<span class="brand-tag" id="brandTag">spec → openapi → client → ui</span>
</div>
<div class="topbar-status">
<span id="healthPill" class="pill pill-pending" title="GET /health"><span class="dot"></span>api…</span>
<a id="contractBadge" class="pill pill-badge" href="/openapi.json" target="_blank" rel="noopener" title="OpenAPI contract">v—</a>
</div>
</div>
</header>
<main class="shell">
<!-- ============ create ============ -->
<section class="card" aria-labelledby="createTitle">
<div class="card-head">
<h2 id="createTitle"><span class="dot"></span>New paste</h2>
</div>
<div class="seg" id="typeSeg" role="tablist" aria-label="paste type">
<button class="seg-btn on" data-t="text" role="tab" aria-selected="true">Text</button>
<button class="seg-btn" data-t="image" role="tab" aria-selected="false">Image</button>
<button class="seg-btn" data-t="file" role="tab" aria-selected="false">File</button>
</div>
<div class="field-row">
<div class="field">
<label for="title">Title <span class="opt">optional</span></label>
<input type="text" id="title" placeholder="unnamed paste" maxlength="200" autocomplete="off">
</div>
<div class="field field-narrow">
<label for="expiry">Expiry</label>
<select id="expiry">
<option value="1h">1 hour</option>
<option value="1d" selected>1 day</option>
<option value="1w">1 week</option>
<option value="1m">1 month</option>
<option value="forever">Never</option>
</select>
</div>
</div>
<div id="paneText">
<label for="content">Content</label>
<textarea id="content" spellcheck="false" placeholder="Paste your text here…"></textarea>
<div class="charcount"><span id="charCount">0</span> chars</div>
</div>
<div id="paneFile" hidden>
<div id="dropzone" tabindex="0" role="button" aria-label="choose a file">
<div class="dz-idle" id="dzIdle">
<div class="dz-icon" aria-hidden="true">⬆</div>
<div class="dz-text">Drop a file here, or <span class="accent">browse</span></div>
<div class="dz-sub" id="dzSub">png · jpeg · gif · bmp · webp · svg · tiff — max 20 MB</div>
</div>
<div class="dz-preview" id="dzPreview" hidden>
<img id="dzThumb" alt="" hidden>
<div class="dz-file-ico" id="dzFileIco" hidden aria-hidden="true">📄</div>
<div style="min-width:0">
<div class="dz-name" id="dzName"></div>
<div class="dz-sub" id="dzMeta"></div>
</div>
<button class="dz-remove" id="dzRemove" title="Remove file" aria-label="Remove file">×</button>
</div>
</div>
<!-- visible to the a11y tree (Chromium renders file inputs as buttons);
the dropzone is the styled affordance, this drives the picker -->
<input type="file" id="fileInput" style="position:absolute;width:1px;height:1px;opacity:0;pointer-events:none"
aria-label="file upload input">
</div>
<div class="card-actions">
<button class="btn btn-primary" id="createBtn">Create paste</button>
<span class="hint" id="createHint"></span>
</div>
</section>
<!-- ============ view ============ -->
<section class="card" aria-labelledby="viewTitle">
<div class="card-head">
<h2 id="viewTitle"><span class="dot"></span>View a paste</h2>
</div>
<div class="open-row">
<input type="text" id="openId" class="mono" placeholder="16-hex id — e.g. 21804754ee2c4e6e" spellcheck="false" autocomplete="off" aria-label="paste id">
<button class="btn btn-ghost" id="openBtn">Open</button>
</div>
<div class="field-err" id="openErr" hidden></div>
<div class="stage" id="stage" aria-live="polite">
<div class="stage-empty">
<div class="stage-empty-ico" aria-hidden="true">📋</div>
<div>Open a paste to see it here.</div>
<div class="stage-empty-sub">text · image · file — with raw &amp; download links</div>
</div>
</div>
<div class="view-meta" id="viewMeta" hidden></div>
<div class="view-actions" id="viewActions" hidden>
<a class="btn btn-ghost btn-sm" id="actRaw" target="_blank" rel="noopener">Raw</a>
<a class="btn btn-ghost btn-sm" id="actDownload">Download</a>
<button class="btn btn-ghost btn-sm" id="actCopyJson">Copy JSON</button>
<button class="btn btn-ghost btn-sm" id="actCopyId">Copy ID</button>
</div>
<div class="recent">
<div class="recent-head">
<span>Recent — this browser</span>
<button class="linklike" id="recentClear" hidden>clear all</button>
</div>
<div class="chips" id="chips">
<span class="chips-empty" id="chipsEmpty">nothing yet — pastes you create land here</span>
</div>
</div>
</section>
</main>
<div class="toasts" id="toasts" aria-live="polite"></div>
<script src="/client.js"></script>
<script src="/app.js"></script>
</body>
</html>

View File

@ -1,451 +0,0 @@
{
"openapi": "3.1.0",
"info": {
"title": "paste_bin",
"version": "1.0.0",
"description": "JSON API contract for paste_bin. Emitted deterministically from the signed arch-llm spec; error literals and defaults are pinned in the source descs."
},
"servers": [
{
"url": "/",
"description": "same-origin (serve UI + API under one origin)"
}
],
"paths": {
"/pastes": {
"post": {
"operationId": "postPastes",
"description": "multipart/form-data fields; ALL form fields have defaults so file-only uploads work without a content field (paste_type default 'text', title default '', expiry default '1d', content default '') and file is an optional UploadFile; rate limit FIRST: _limiter.allow(client IP) False -> 429 {error: 'Too many uploads. Please wait.'}; then parse_expiry(expiry), ValueError -> 400 {error: 'Invalid expiry'}; paste_type 'text': content must be non-empty after strip else 400 {error: 'Content cannot be empty'}; STORE content verbatim, never stripped (old app stripped stored content \u2014 fixed); paste_type 'image': no file -> 400 {error: 'No file selected'}; sanitize_filename, empty -> 400 same; extension must be an allowed image extension else 400 {error: 'Invalid image format'}; check_image_magic on the first 12 bytes else 400 {error: 'File content does not match image type.'}; read all bytes, len > MAX_UPLOAD_BYTES -> 413 {error: 'File too large. Maximum size is 20 MB.'}; write_upload; meta type 'image', title or original filename, mimetype derive_mimetype(ext), created_at ISO UTC, expires_at from parse_expiry; paste_type 'file': same no-file/sanitize checks; if is_text_ext: read bytes, decode utf-8 errors=replace, store as a 'text' paste WITH filename in meta; else: 20MB check, write_upload, meta type 'file', mimetype derive_mimetype(ext); any other paste_type -> 400 {error: 'Invalid paste type'}; the meta dict passed to save_meta uses EXACTLY the Paste record field names as keys (type, title, created_at, expires_at, filename, mimetype, filepath \u2014 never 'path'); success 201 PasteOut {id, title, type, created_at, expires_at, view: '/pastes/<id>', raw: '/pastes/<id>/raw', download: '/pastes/<id>/download'}",
"x-error-literals": {
"400": [
"Content cannot be empty",
"File content does not match image type.",
"Invalid expiry",
"Invalid image format",
"Invalid paste type",
"No file selected"
],
"413": [
"File too large. Maximum size is 20 MB."
],
"429": [
"Too many uploads. Please wait."
]
},
"requestBody": {
"required": true,
"content": {
"multipart/form-data": {
"schema": {
"type": "object",
"properties": {
"paste_type": {
"type": "string",
"default": "text"
},
"title": {
"type": "string",
"default": ""
},
"expiry": {
"type": "string",
"default": "1d"
},
"content": {
"type": "string",
"default": ""
},
"file": {
"type": "string",
"format": "binary"
}
}
}
}
}
},
"responses": {
"201": {
"description": "201",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/PasteOut"
}
}
}
},
"400": {
"description": "Content cannot be empty",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrOut"
}
}
}
},
"413": {
"description": "File too large. Maximum size is 20 MB.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrOut"
}
}
}
},
"429": {
"description": "Too many uploads. Please wait.",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrOut"
}
}
}
}
}
}
},
"/pastes/{paste_id}": {
"get": {
"operationId": "getPastesPaste_id",
"description": "load_meta None -> 404 {error: 'Paste not found'}; expired -> store.delete then 404 same body; text pastes: ViewOut with content read_content or '', filename from meta (set when the paste was created from an uploaded text file, else None), mimetype None; image/file: content None, filename and mimetype from meta",
"x-error-literals": {
"404": [
"Paste not found"
]
},
"responses": {
"200": {
"description": "200",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ViewOut"
}
}
}
},
"404": {
"description": "Paste not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrOut"
}
}
}
}
}
},
"parameters": [
{
"name": "paste_id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"pattern": "^[a-f0-9]{16}$"
}
}
]
},
"/pastes/{paste_id}/download": {
"get": {
"operationId": "getPastesPaste_idDownload",
"description": "same 404/expiry-delete handling (uploaded file path read from meta['filepath']); text -> the content utf-8 bytes as an attachment, filename meta['filename'] or 'paste.txt', media type text/plain; image/file -> the uploaded file's bytes as an attachment, filename meta['filename'], media type meta['mimetype']; uploaded file missing on disk -> 404 {error: 'Paste not found'}",
"x-error-literals": {
"404": [
"Paste not found"
]
},
"responses": {
"200": {
"description": "200",
"content": {
"application/octet-stream": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
},
"404": {
"description": "Paste not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrOut"
}
}
}
}
}
},
"parameters": [
{
"name": "paste_id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"pattern": "^[a-f0-9]{16}$"
}
}
]
},
"/pastes/{paste_id}/raw": {
"get": {
"operationId": "getPastesPaste_idRaw",
"description": "same 404/expiry-delete handling (uploaded file path read from meta['filepath']); text -> content utf-8 bytes, media type text/plain; charset=utf-8, no attachment; image -> uploaded file bytes, media type meta['mimetype']; file -> uploaded file bytes, media type meta['mimetype'] (old app fell through and 500'd for file pastes \u2014 fixed); uploaded file missing on disk -> 404 {error: 'Paste not found'}",
"x-error-literals": {
"404": [
"Paste not found"
]
},
"responses": {
"200": {
"description": "200",
"content": {
"application/octet-stream": {
"schema": {
"type": "string",
"format": "binary"
}
}
}
},
"404": {
"description": "Paste not found",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrOut"
}
}
}
}
}
},
"parameters": [
{
"name": "paste_id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"pattern": "^[a-f0-9]{16}$"
}
}
]
},
"/health": {
"get": {
"operationId": "getHealth",
"description": "{status: 'ok'}",
"responses": {
"200": {
"description": "200",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HealthOut"
}
}
}
}
}
}
},
"/": {
"get": {
"operationId": "getIndex",
"description": "{service: 'paste-bin', endpoints: ['/pastes', '/health']}",
"responses": {
"200": {
"description": "200",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/IndexOut"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Paste": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"title": {
"type": "string"
},
"created_at": {
"type": "string"
},
"expires_at": {
"type": "string",
"nullable": true
},
"filename": {
"type": "string",
"nullable": true
},
"mimetype": {
"type": "string",
"nullable": true
},
"filepath": {
"type": "string",
"nullable": true
}
},
"required": [
"type",
"title",
"created_at"
],
"description": "one paste's metadata, stored as JSON at store_dir/<id>; the on-disk JSON keys are EXACTLY these field names; type is 'text' | 'image' | 'file'; filepath set for image/file pastes (absolute path in upload_dir), None for text"
},
"ErrOut": {
"type": "object",
"properties": {
"error": {
"type": "string"
}
},
"required": [
"error"
]
},
"PasteOut": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"title": {
"type": "string"
},
"type": {
"type": "string"
},
"created_at": {
"type": "string"
},
"expires_at": {
"type": "string",
"nullable": true
},
"view": {
"type": "string"
},
"raw": {
"type": "string"
},
"download": {
"type": "string"
}
},
"required": [
"id",
"title",
"type",
"created_at",
"view",
"raw",
"download"
]
},
"ViewOut": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"type": {
"type": "string"
},
"title": {
"type": "string"
},
"created_at": {
"type": "string"
},
"expires_at": {
"type": "string",
"nullable": true
},
"content": {
"type": "string",
"nullable": true
},
"filename": {
"type": "string",
"nullable": true
},
"mimetype": {
"type": "string",
"nullable": true
}
},
"required": [
"id",
"type",
"title",
"created_at"
]
},
"HealthOut": {
"type": "object",
"properties": {
"status": {
"type": "string"
}
},
"required": [
"status"
]
},
"IndexOut": {
"type": "object",
"properties": {
"service": {
"type": "string"
},
"endpoints": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"service",
"endpoints"
]
}
}
},
"x-contract-notes": {
"modules": {
"validate": "pure validation helpers: paste ids, expiry parsing, filename sanitizing, image magic-byte checks, mimetype derivation; no I/O, no state\nmodule constants: ALLOWED_IMAGE_EXTENSIONS = {png, jpg, jpeg, gif, bmp, webp, tiff}; ALLOWED_TEXT_EXTENSIONS = {txt, py, js, ts, c, cpp, h, java, rb, go, rs, md, json, xml, yaml, yml, html, css, sh, log, csv, sql, ini, cfg, toml, lua, php, swift, kt, scala, r, pl, hs, zig, nix}; MAX_UPLOAD_BYTES = 20 * 1024 * 1024",
"store": "file-backed paste persistence: store_dir holds JSON metadata at <id> and text content at <id>.txt; upload_dir holds binary uploads at <id>.<ext>; all metadata writes are atomic\nis_valid_paste_id is imported from paste_bin.validate at module top level \u2014 the single source of truth, never redefined or reimplemented locally",
"ratelimit": "per-IP sliding-window rate limiter for paste uploads, in-process state",
"headers": "security response headers for every response",
"api": "FastAPI multipart router over the store; at import time build a module-level PasteStore named _store from env STORE_FOLDER (default 'store') and env UPLOAD_FOLDER (default 'uploads') and call _store.start_cleanup_loop() on it; also a module-level UploadRateLimiter named _limiter constructed with bare class defaults \u2014 exactly `_limiter = UploadRateLimiter()` (10 attempts per 60s window; NO config indirection, NO inflated limits); every route merges security_headers(is_secure=<request scheme is https>) into the response headers\nerrors are JSON {error: str} with the pinned status; success bodies are the records below\nFlask compatibility: every GET route must also accept HEAD \u2014 same status code and headers as the GET, empty body (declare each GET endpoint with methods=['GET','HEAD']); FastAPI does not auto-add HEAD",
"app": "app entry: create the FastAPI app and mount paste_router"
},
"signoff": "07e1c8b9e27e/ce3bef1efa30 (signed 2026-11-18T18:52:46+00:00)"
}
}

View File

@ -1,911 +0,0 @@
/* ============================================================
paste-bin UI — design system
Palette inherited from the original app (static/style.css):
bg #1a1a2e · panel #16213e · line #0f3460 · accent #e94560
============================================================ */
:root {
--bg: #1a1a2e;
--bg-deep: #131324;
--panel: #16213e;
--panel-2: #101a33;
--panel-3: #0d1730;
--line: #0f3460;
--line-soft: rgba(15, 52, 96, 0.55);
--ink: #e4e6ee;
--ink-dim: #a0a8bd;
--ink-faint: #5f6880;
--accent: #e94560;
--accent-hi: #f05e78;
--accent-soft: rgba(233, 69, 96, 0.13);
--ok: #3ddc84;
--warn: #f5a623;
--mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, Consolas,
"Liberation Mono", monospace;
--sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, sans-serif;
--radius: 12px;
--radius-sm: 8px;
--shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
color-scheme: dark;
}
body {
font-family: var(--sans);
font-size: 15px;
line-height: 1.55;
color: var(--ink);
background:
radial-gradient(1100px 480px at 75% -10%, rgba(233, 69, 96, 0.07), transparent 60%),
radial-gradient(900px 420px at -10% 110%, rgba(15, 52, 96, 0.5), transparent 60%),
var(--bg);
min-height: 100vh;
}
a {
color: var(--accent-hi);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 4px;
}
/* ---------- top bar ---------- */
.topbar {
position: sticky;
top: 0;
z-index: 20;
background: rgba(19, 19, 36, 0.82);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--line-soft);
}
.topbar-inner {
max-width: 1120px;
margin: 0 auto;
padding: 12px 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.brand {
display: flex;
align-items: baseline;
gap: 10px;
min-width: 0;
}
.brand-mark {
font-size: 19px;
align-self: center;
}
.brand-name {
font-size: 19px;
font-weight: 700;
letter-spacing: -0.01em;
}
.brand-name .accent {
color: var(--accent);
}
.brand-tag {
color: var(--ink-faint);
font-size: 12px;
font-family: var(--mono);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.topbar-status {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.pill {
display: inline-flex;
align-items: center;
gap: 7px;
font-size: 12px;
font-family: var(--mono);
padding: 4px 11px;
border-radius: 999px;
border: 1px solid var(--line);
background: var(--panel-2);
color: var(--ink-dim);
white-space: nowrap;
}
.pill .dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--ink-faint);
flex-shrink: 0;
}
.pill-ok {
color: var(--ok);
border-color: rgba(61, 220, 132, 0.35);
}
.pill-ok .dot {
background: var(--ok);
box-shadow: 0 0 8px rgba(61, 220, 132, 0.7);
}
.pill-err {
color: var(--accent-hi);
border-color: rgba(233, 69, 96, 0.4);
}
.pill-err .dot {
background: var(--accent);
}
.pill-pending .dot {
animation: pulse 1.2s ease-in-out infinite;
}
.pill-badge {
text-decoration: none;
cursor: pointer;
transition: border-color 0.15s, color 0.15s;
}
.pill-badge:hover {
color: var(--ink);
border-color: var(--accent);
text-decoration: none;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.25; }
}
/* ---------- layout ---------- */
.shell {
max-width: 1120px;
margin: 0 auto;
padding: 26px 20px 60px;
display: grid;
grid-template-columns: 1.08fr 1fr;
gap: 20px;
align-items: start;
}
.card {
background: var(--panel);
border: 1px solid var(--line-soft);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 22px;
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
}
.card-head h2 {
display: flex;
align-items: center;
gap: 9px;
font-size: 13px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.09em;
color: var(--ink-dim);
}
.card-head h2 .dot {
width: 8px;
height: 8px;
border-radius: 3px;
background: var(--accent);
flex-shrink: 0;
}
/* ---------- segmented control ---------- */
.seg {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 4px;
background: var(--panel-3);
border: 1px solid var(--line-soft);
border-radius: 10px;
padding: 4px;
margin-bottom: 18px;
}
.seg-btn {
font: inherit;
font-size: 14px;
font-weight: 500;
color: var(--ink-dim);
background: transparent;
border: 1px solid transparent;
border-radius: 7px;
padding: 8px 10px;
cursor: pointer;
transition: color 0.15s, background 0.15s, border-color 0.15s;
}
.seg-btn:hover {
color: var(--ink);
}
.seg-btn.on {
color: var(--accent-hi);
background: var(--accent-soft);
border-color: rgba(233, 69, 96, 0.45);
font-weight: 600;
}
/* ---------- form fields ---------- */
.field-row {
display: flex;
gap: 14px;
margin-bottom: 16px;
}
.field {
flex: 1;
min-width: 0;
}
.field-narrow {
flex: 0 0 148px;
}
label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--ink-dim);
}
label .opt {
color: var(--ink-faint);
font-weight: 400;
font-size: 12px;
}
input[type="text"],
textarea,
select {
width: 100%;
font: inherit;
color: var(--ink);
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 9px 12px;
transition: border-color 0.15s, box-shadow 0.15s;
}
input::placeholder,
textarea::placeholder {
color: var(--ink-faint);
}
input[type="text"]:focus,
textarea:focus,
select:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-soft);
}
.mono {
font-family: var(--mono);
font-size: 13.5px;
letter-spacing: 0.02em;
}
select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%23a0a8bd' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 12px center;
padding-right: 30px;
}
textarea {
resize: vertical;
min-height: 220px;
font-family: var(--mono);
font-size: 13.5px;
line-height: 1.6;
}
.charcount {
margin-top: 6px;
text-align: right;
font-size: 12px;
font-family: var(--mono);
color: var(--ink-faint);
}
.pane[hidden] {
display: none;
}
/* ---------- dropzone ---------- */
#dropzone {
border: 2px dashed var(--line);
border-radius: var(--radius);
background: var(--panel-2);
padding: 22px;
cursor: pointer;
transition: border-color 0.15s, background 0.15s;
position: relative;
}
#dropzone:hover,
#dropzone:focus-visible {
border-color: var(--accent);
}
#dropzone.dragover {
border-color: var(--accent-hi);
background: var(--accent-soft);
}
.dz-idle {
text-align: center;
padding: 14px 0;
}
.dz-icon {
font-size: 26px;
margin-bottom: 6px;
color: var(--accent);
}
.dz-text {
color: var(--ink-dim);
font-size: 14.5px;
}
.dz-text .accent {
color: var(--accent-hi);
font-weight: 600;
}
.dz-sub {
margin-top: 5px;
font-size: 12px;
color: var(--ink-faint);
font-family: var(--mono);
}
.dz-preview {
display: flex;
align-items: center;
gap: 14px;
}
.dz-preview img {
width: 72px;
height: 72px;
object-fit: cover;
border-radius: var(--radius-sm);
border: 1px solid var(--line);
background: var(--panel-3);
}
.dz-file-ico {
font-size: 34px;
width: 72px;
text-align: center;
}
.dz-name {
font-weight: 600;
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 320px;
}
.dz-remove {
margin-left: auto;
flex-shrink: 0;
width: 28px;
height: 28px;
border-radius: 50%;
border: 1px solid var(--line);
background: var(--panel-3);
color: var(--ink-dim);
font-size: 15px;
line-height: 1;
cursor: pointer;
transition: color 0.15s, border-color 0.15s;
}
.dz-remove:hover {
color: var(--accent-hi);
border-color: var(--accent);
}
/* ---------- buttons ---------- */
.btn {
font: inherit;
font-size: 14px;
font-weight: 600;
border-radius: var(--radius-sm);
padding: 10px 18px;
cursor: pointer;
border: 1px solid transparent;
transition: background 0.15s, border-color 0.15s, color 0.15s,
transform 0.06s, box-shadow 0.15s;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn:active {
transform: translateY(1px);
}
.btn:disabled {
opacity: 0.55;
cursor: not-allowed;
transform: none;
}
.btn-primary {
background: var(--accent);
color: #fff;
box-shadow: 0 4px 14px rgba(233, 69, 96, 0.3);
}
.btn-primary:hover:not(:disabled) {
background: var(--accent-hi);
box-shadow: 0 6px 18px rgba(233, 69, 96, 0.4);
}
.btn-ghost {
background: transparent;
color: var(--accent-hi);
border-color: rgba(233, 69, 96, 0.5);
}
.btn-ghost:hover:not(:disabled) {
background: var(--accent-soft);
border-color: var(--accent);
text-decoration: none;
}
.btn-sm {
font-size: 13px;
font-weight: 500;
padding: 6px 12px;
}
.linklike {
font: inherit;
font-size: 12px;
color: var(--ink-faint);
background: none;
border: none;
cursor: pointer;
padding: 0;
}
.linklike:hover {
color: var(--accent-hi);
}
.card-actions {
display: flex;
align-items: center;
gap: 12px;
margin-top: 18px;
}
.hint {
font-size: 12.5px;
color: var(--ink-faint);
}
/* ---------- open row ---------- */
.open-row {
display: flex;
gap: 10px;
}
.open-row input {
flex: 1;
min-width: 0;
}
.field-err {
margin-top: 8px;
font-size: 13px;
color: var(--accent-hi);
}
.field-err[hidden] {
display: none;
}
/* ---------- view stage ---------- */
.stage {
margin-top: 16px;
min-height: 210px;
border: 1px solid var(--line-soft);
border-radius: var(--radius);
background: var(--panel-2);
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.stage-empty {
text-align: center;
color: var(--ink-faint);
padding: 40px 20px;
}
.stage-empty-ico {
font-size: 34px;
margin-bottom: 10px;
opacity: 0.8;
}
.stage-empty-sub {
margin-top: 5px;
font-size: 12px;
font-family: var(--mono);
color: var(--ink-faint);
opacity: 0.7;
}
.stage-loading {
color: var(--ink-dim);
font-size: 14px;
font-family: var(--mono);
display: flex;
align-items: center;
gap: 10px;
}
.stage-loading .spinner {
width: 14px;
height: 14px;
border: 2px solid var(--line);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.view-text {
width: 100%;
max-height: 400px;
overflow: auto;
padding: 16px 18px;
font-family: var(--mono);
font-size: 13.5px;
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
color: var(--ink);
}
.stage-img {
padding: 18px;
display: flex;
justify-content: center;
background: repeating-conic-gradient(
var(--panel-3) 0% 25%,
var(--panel-2) 0% 50%
)
0 0 / 18px 18px;
}
.stage-img img {
max-width: 100%;
max-height: 400px;
border-radius: var(--radius-sm);
border: 1px solid var(--line);
box-shadow: var(--shadow);
}
.view-file {
text-align: center;
padding: 40px 20px;
}
.view-file-ico {
font-size: 44px;
margin-bottom: 12px;
}
.view-file-name {
font-weight: 600;
font-size: 15px;
overflow-wrap: anywhere;
}
.view-file-sub {
margin-top: 5px;
font-size: 12.5px;
font-family: var(--mono);
color: var(--ink-faint);
}
.view-error {
text-align: center;
padding: 36px 20px;
}
.view-error-ico {
font-size: 30px;
margin-bottom: 10px;
}
.view-error-title {
color: var(--accent-hi);
font-weight: 600;
font-size: 15px;
}
.view-error-sub {
margin-top: 6px;
font-size: 13px;
color: var(--ink-faint);
font-family: var(--mono);
}
/* ---------- meta + actions ---------- */
.view-meta {
margin-top: 12px;
font-size: 12.5px;
font-family: var(--mono);
color: var(--ink-faint);
line-height: 1.7;
overflow-wrap: anywhere;
}
.view-meta[hidden] {
display: none;
}
.view-meta b {
color: var(--ink-dim);
font-weight: 500;
}
.view-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.view-actions[hidden] {
display: none;
}
/* ---------- recent chips ---------- */
.recent {
margin-top: 22px;
border-top: 1px solid var(--line-soft);
padding-top: 14px;
}
.recent-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--ink-faint);
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.chips-empty {
font-size: 13px;
color: var(--ink-faint);
}
.chip {
display: inline-flex;
align-items: center;
gap: 8px;
background: var(--panel-2);
border: 1px solid var(--line);
border-radius: 999px;
padding: 5px 6px 5px 12px;
cursor: pointer;
transition: border-color 0.15s, background 0.15s;
max-width: 100%;
}
.chip:hover {
border-color: var(--accent);
background: var(--accent-soft);
}
.chip-ico {
font-size: 13px;
}
.chip-id {
font-family: var(--mono);
font-size: 12.5px;
color: var(--ink);
}
.chip-title {
font-size: 12.5px;
color: var(--ink-faint);
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chip-x {
border: none;
background: none;
color: var(--ink-faint);
font-size: 14px;
cursor: pointer;
padding: 2px 5px;
border-radius: 50%;
line-height: 1;
}
.chip-x:hover {
color: var(--accent-hi);
background: rgba(233, 69, 96, 0.18);
}
/* ---------- toasts ---------- */
.toasts {
position: fixed;
right: 18px;
bottom: 18px;
z-index: 50;
display: flex;
flex-direction: column;
gap: 10px;
max-width: min(380px, calc(100vw - 36px));
}
.toast {
background: var(--panel);
border: 1px solid var(--line);
border-left: 3px solid var(--ink-faint);
border-radius: var(--radius-sm);
box-shadow: var(--shadow);
padding: 12px 34px 12px 14px;
position: relative;
opacity: 0;
transform: translateY(10px);
transition: opacity 0.25s, transform 0.25s;
}
.toast.in {
opacity: 1;
transform: translateY(0);
}
.toast-title {
font-size: 13.5px;
font-weight: 600;
font-family: var(--mono);
overflow-wrap: anywhere;
}
.toast-detail {
margin-top: 3px;
font-size: 12.5px;
color: var(--ink-dim);
overflow-wrap: anywhere;
}
.toast-ok {
border-left-color: var(--ok);
}
.toast-ok .toast-title {
color: var(--ok);
}
.toast-warn {
border-left-color: var(--warn);
}
.toast-warn .toast-title {
color: var(--warn);
}
.toast-err {
border-left-color: var(--accent);
}
.toast-err .toast-title {
color: var(--accent-hi);
}
.toast-x {
position: absolute;
top: 8px;
right: 8px;
border: none;
background: none;
color: var(--ink-faint);
font-size: 15px;
cursor: pointer;
padding: 2px 6px;
border-radius: 50%;
line-height: 1;
}
.toast-x:hover {
color: var(--ink);
}
/* ---------- responsive ---------- */
@media (max-width: 940px) {
.shell {
grid-template-columns: 1fr;
padding-top: 18px;
}
.brand-tag {
display: none;
}
}
@media (max-width: 560px) {
.field-row {
flex-direction: column;
gap: 12px;
}
.field-narrow {
flex: 1;
}
.topbar-inner {
flex-wrap: wrap;
}
}