tools/app/tools/paste.py
neil f4232ef9b5 Pastebin limits: 5 MB per paste, 10 per IP and 1000 site-wide per 24 h
Creations are logged in SQLite (IP as an HMAC with a per-install key, kept
24 h), so limits survive restarts and deleting a paste doesn't refund it.
The site-wide cap also bounds storage (~5 GB worst case), replacing the
live-storage cap. Adds an Open file button to the paste page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 23:51:19 -08:00

183 lines
6.4 KiB
Python

"""Pastebin: anonymous text pastes that expire 24 hours after creation.
Storage is one SQLite file in $DATA_DIR. Expired pastes are invisible at once and
deleted by a sweep every few minutes. Anti-abuse is deliberately simple: a size cap
per paste, and creation limits per IP and for the whole site over a rolling 24 hours.
Creations are logged in the database (IP as a keyed hash, kept 24 h), so the limits
survive restarts and deleting a paste doesn't hand its quota back.
"""
import asyncio
import hashlib
import hmac
import json
import os
import secrets
import sqlite3
import threading
import time
from pathlib import Path
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import PlainTextResponse
TTL = 24 * 3600
MAX_BYTES = 5 * 1024 * 1024 # per paste (UTF-8 bytes)
PER_IP_LIMIT = 10 # new pastes per IP ...
SITE_LIMIT = 1000 # ... and for the whole site ...
LIMIT_WINDOW = 24 * 3600 # ... per rolling window (also bounds storage: ~5 GB worst case)
SWEEP_EVERY = 300
DB_PATH = Path(os.environ.get("DATA_DIR", "./data")) / "paste.db"
router = APIRouter()
_lock = threading.Lock()
_ip_key = b""
_sweeper: asyncio.Task | None = None
def _db() -> sqlite3.Connection:
conn = sqlite3.connect(DB_PATH, timeout=10)
conn.row_factory = sqlite3.Row
return conn
def _init():
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
with _db() as c:
c.execute("PRAGMA journal_mode=WAL")
c.execute(
"""CREATE TABLE IF NOT EXISTS pastes (
id TEXT PRIMARY KEY,
content TEXT NOT NULL,
size INTEGER NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
delete_token TEXT NOT NULL
)"""
)
c.execute("CREATE INDEX IF NOT EXISTS pastes_expires ON pastes(expires_at)")
c.execute("CREATE TABLE IF NOT EXISTS creations (ts INTEGER NOT NULL, ip TEXT NOT NULL)")
c.execute("CREATE INDEX IF NOT EXISTS creations_ts ON creations(ts)")
c.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT NOT NULL)")
c.execute("INSERT OR IGNORE INTO meta VALUES ('ip_key', ?)", (secrets.token_hex(32),))
global _ip_key
_ip_key = bytes.fromhex(c.execute("SELECT v FROM meta WHERE k = 'ip_key'").fetchone()[0])
def _sweep() -> int:
now = int(time.time())
with _db() as c:
c.execute("DELETE FROM creations WHERE ts <= ?", (now - LIMIT_WINDOW,))
return c.execute("DELETE FROM pastes WHERE expires_at <= ?", (now,)).rowcount
async def _sweep_loop():
while True:
await asyncio.to_thread(_sweep)
await asyncio.sleep(SWEEP_EVERY)
async def startup():
global _sweeper
_init()
_sweeper = asyncio.create_task(_sweep_loop())
async def shutdown():
if _sweeper:
_sweeper.cancel()
def client_ip(request: Request) -> str:
# uvicorn runs with --proxy-headers --forwarded-allow-ips 127.0.0.1, so behind
# a reverse proxy that connects over loopback this is already the visitor's address.
return request.client.host if request.client else ""
def _ip_hash(ip: str) -> str:
return hmac.new(_ip_key, ip.encode(), hashlib.sha256).hexdigest()[:32]
def _get(pid: str) -> sqlite3.Row:
with _db() as c:
row = c.execute(
"SELECT id, content, size, created_at, expires_at FROM pastes WHERE id = ? AND expires_at > ?",
(pid, int(time.time())),
).fetchone()
if not row:
raise HTTPException(404, "This paste doesn't exist or has expired.")
return row
@router.post("/api/paste", status_code=201)
async def create(request: Request):
too_big = HTTPException(413, f"Paste is larger than {MAX_BYTES // 1024 // 1024} MB.")
body = bytearray()
async for chunk in request.stream():
body += chunk
if len(body) > 2 * MAX_BYTES + 64 * 1024: # room for JSON escaping (\n, \", …)
raise too_big
try:
data = json.loads(body)
content = data["content"]
assert isinstance(content, str)
except Exception:
raise HTTPException(400, 'Expected JSON: {"content": "<text>"}')
size = len(content.encode())
if not content.strip():
raise HTTPException(400, "Paste is empty.")
if size > MAX_BYTES:
raise too_big
now = int(time.time())
since = now - LIMIT_WINDOW
ip = _ip_hash(client_ip(request))
pid, token = secrets.token_urlsafe(6), secrets.token_urlsafe(18)
with _lock, _db() as c:
if c.execute("SELECT COUNT(*) FROM creations WHERE ts > ? AND ip = ?", (since, ip)).fetchone()[0] >= PER_IP_LIMIT:
raise HTTPException(429, f"You've reached the limit of {PER_IP_LIMIT} pastes per 24 hours. Try again later.")
if c.execute("SELECT COUNT(*) FROM creations WHERE ts > ?", (since,)).fetchone()[0] >= SITE_LIMIT:
raise HTTPException(429, f"The site has reached its limit of {SITE_LIMIT} pastes per 24 hours. Try again later.")
c.execute("INSERT INTO creations (ts, ip) VALUES (?, ?)", (now, ip))
c.execute(
"INSERT INTO pastes (id, content, size, created_at, expires_at, delete_token) VALUES (?, ?, ?, ?, ?, ?)",
(pid, content, size, now, now + TTL, token),
)
return {"id": pid, "expires_at": now + TTL, "delete_token": token}
@router.get("/api/paste/{pid}")
def read(pid: str):
row = _get(pid)
return {
"id": row["id"],
"content": row["content"],
"size": row["size"],
"created_at": row["created_at"],
"expires_at": row["expires_at"],
}
@router.delete("/api/paste/{pid}", status_code=204)
def delete(pid: str, request: Request):
token = request.headers.get("x-delete-token", "")
with _db() as c:
row = c.execute("SELECT delete_token FROM pastes WHERE id = ?", (pid,)).fetchone()
if not row or not secrets.compare_digest(row["delete_token"], token):
raise HTTPException(404, "Not found, or wrong delete token.")
c.execute("DELETE FROM pastes WHERE id = ?", (pid,))
@router.get("/raw/{pid}", response_class=PlainTextResponse)
def raw(pid: str):
row = _get(pid)
return PlainTextResponse(
row["content"],
headers={
# Never let a paste act as a web page on this origin.
"Content-Security-Policy": "default-src 'none'; sandbox",
"X-Robots-Tag": "noindex",
"Cache-Control": "no-store",
},
)