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>
This commit is contained in:
neil 2026-11-01 23:51:19 -08:00
parent 792d48553c
commit f4232ef9b5
3 changed files with 50 additions and 36 deletions

View file

@ -55,7 +55,9 @@ on the same host in front of it.
## Pastebin limits ## Pastebin limits
1 MiB per paste, 256 MiB of live pastes in total, 30 new pastes per IP per hour. Expired 5 MB per paste, 10 new pastes per IP and 1000 for the whole site per rolling 24 hours
(logged in the DB with the IP as a keyed hash, so limits survive restarts and deleting a paste
doesn't refund it). Expired
pastes stop being served immediately and are deleted every 5 minutes. `/raw/<id>` is served pastes stop being served immediately and are deleted every 5 minutes. `/raw/<id>` is served
as `text/plain` with a sandboxing CSP, so a paste can never run as a page on this origin. as `text/plain` with a sandboxing CSP, so a paste can never run as a page on this origin.
Each paste gets a delete token, kept in the creating browser's localStorage. Each paste gets a delete token, kept in the creating browser's localStorage.

View file

@ -1,8 +1,8 @@
// Pastebin: /paste to create, /paste/<id> to view. Pastes expire 24 h after creation. // Pastebin: /paste to create, /paste/<id> to view. Pastes expire 24 h after creation.
// Pastes made in this browser are remembered locally (with their delete tokens). // Pastes made in this browser are remembered locally (with their delete tokens).
import { el, store, copyText, downloadText, toast, timeLeft, formatBytes } from '../ui.js'; import { el, store, copyText, downloadText, openTextFile, toast, timeLeft, formatBytes } from '../ui.js';
const MAX_BYTES = 1024 * 1024; const MAX_BYTES = 5 * 1024 * 1024; // keep in step with app/tools/paste.py
function mine() { function mine() {
const now = Date.now() / 1000; const now = Date.now() / 1000;
@ -54,7 +54,7 @@ function renderCreate(root, ctx, timers) {
const btn = el('button.btn.primary', { onclick: submit }, 'Create paste'); const btn = el('button.btn.primary', { onclick: submit }, 'Create paste');
const updateInfo = () => { const updateInfo = () => {
const n = new Blob([ta.value]).size; const n = new Blob([ta.value]).size;
info.textContent = `${formatBytes(n)} of 1 MB · expires 24 h after creation`; info.textContent = `${formatBytes(n)} of 5 MB · expires 24 h after creation`;
info.classList.toggle('error-text', n > MAX_BYTES); info.classList.toggle('error-text', n > MAX_BYTES);
}; };
ta.addEventListener('input', () => { ta.addEventListener('input', () => {
@ -65,9 +65,17 @@ function renderCreate(root, ctx, timers) {
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit(); if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit();
}); });
async function openFile() {
const f = await openTextFile();
if (!f) return;
if (f.text.includes('\u0000')) return toast(`${f.name} looks like a binary file; only text can be pasted`, 'error');
ta.value = f.text;
ta.dispatchEvent(new Event('input'));
}
async function submit() { async function submit() {
if (!ta.value.trim()) return toast('Nothing to paste', 'error'); if (!ta.value.trim()) return toast('Nothing to paste', 'error');
if (new Blob([ta.value]).size > MAX_BYTES) return toast('Paste is larger than 1 MB', 'error'); if (new Blob([ta.value]).size > MAX_BYTES) return toast('Paste is larger than 5 MB', 'error');
btn.disabled = true; btn.disabled = true;
const p = await createPaste(ta.value); const p = await createPaste(ta.value);
btn.disabled = false; btn.disabled = false;
@ -102,8 +110,9 @@ function renderCreate(root, ctx, timers) {
root.append( root.append(
el('div.tool.paste-tool', {}, el('div.tool.paste-tool', {},
el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info, btn), el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info,
el('div.paste-body', {}, ta, el('div.hint.muted.small', {}, 'Ctrl+Enter to create. Anyone with the link can read it until it expires. Don\'t paste secrets.'), list), el('button.btn', { onclick: openFile, title: 'Load a text file (up to 5 MB)' }, 'Open file'), btn),
el('div.paste-body', {}, ta, el('div.hint.muted.small', {}, 'Ctrl+Enter to create. Anyone with the link can read it until it expires. Don\'t paste secrets. Limit: 10 pastes per person per day.'), list),
), ),
); );
ta.focus(); ta.focus();

View file

@ -2,34 +2,37 @@
Storage is one SQLite file in $DATA_DIR. Expired pastes are invisible at once and 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 deleted by a sweep every few minutes. Anti-abuse is deliberately simple: a size cap
per paste, a cap on total live storage, and a per-IP creation rate limit. 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 asyncio
import hashlib
import hmac
import json import json
import os import os
import secrets import secrets
import sqlite3 import sqlite3
import threading import threading
import time import time
from collections import defaultdict, deque
from pathlib import Path from pathlib import Path
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import PlainTextResponse from fastapi.responses import PlainTextResponse
TTL = 24 * 3600 TTL = 24 * 3600
MAX_BYTES = 1024 * 1024 # per paste MAX_BYTES = 5 * 1024 * 1024 # per paste (UTF-8 bytes)
MAX_TOTAL_BYTES = 256 * 1024 * 1024 # all live pastes together PER_IP_LIMIT = 10 # new pastes per IP ...
RATE_LIMIT = 30 # creations per IP ... SITE_LIMIT = 1000 # ... and for the whole site ...
RATE_WINDOW = 3600 # ... per this many seconds LIMIT_WINDOW = 24 * 3600 # ... per rolling window (also bounds storage: ~5 GB worst case)
SWEEP_EVERY = 300 SWEEP_EVERY = 300
DB_PATH = Path(os.environ.get("DATA_DIR", "./data")) / "paste.db" DB_PATH = Path(os.environ.get("DATA_DIR", "./data")) / "paste.db"
router = APIRouter() router = APIRouter()
_lock = threading.Lock() _lock = threading.Lock()
_recent: dict[str, deque] = defaultdict(deque) _ip_key = b""
_sweeper: asyncio.Task | None = None _sweeper: asyncio.Task | None = None
@ -54,11 +57,19 @@ def _init():
)""" )"""
) )
c.execute("CREATE INDEX IF NOT EXISTS pastes_expires ON pastes(expires_at)") 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: def _sweep() -> int:
now = int(time.time())
with _db() as c: with _db() as c:
return c.execute("DELETE FROM pastes WHERE expires_at <= ?", (int(time.time()),)).rowcount 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(): async def _sweep_loop():
@ -84,19 +95,8 @@ def client_ip(request: Request) -> str:
return request.client.host if request.client else "" return request.client.host if request.client else ""
def _rate_limited(ip: str) -> bool: def _ip_hash(ip: str) -> str:
now = time.monotonic() return hmac.new(_ip_key, ip.encode(), hashlib.sha256).hexdigest()[:32]
with _lock:
q = _recent[ip]
while q and q[0] <= now - RATE_WINDOW:
q.popleft()
if len(q) >= RATE_LIMIT:
return True
q.append(now)
if len(_recent) > 10000: # drop idle entries so the map can't grow forever
for k in [k for k, v in _recent.items() if not v]:
del _recent[k]
return False
def _get(pid: str) -> sqlite3.Row: def _get(pid: str) -> sqlite3.Row:
@ -112,11 +112,12 @@ def _get(pid: str) -> sqlite3.Row:
@router.post("/api/paste", status_code=201) @router.post("/api/paste", status_code=201)
async def create(request: Request): async def create(request: Request):
too_big = HTTPException(413, f"Paste is larger than {MAX_BYTES // 1024 // 1024} MB.")
body = bytearray() body = bytearray()
async for chunk in request.stream(): async for chunk in request.stream():
body += chunk body += chunk
if len(body) > MAX_BYTES + 64 * 1024: if len(body) > 2 * MAX_BYTES + 64 * 1024: # room for JSON escaping (\n, \", …)
raise HTTPException(413, "Paste is larger than 1 MiB.") raise too_big
try: try:
data = json.loads(body) data = json.loads(body)
content = data["content"] content = data["content"]
@ -127,16 +128,18 @@ async def create(request: Request):
if not content.strip(): if not content.strip():
raise HTTPException(400, "Paste is empty.") raise HTTPException(400, "Paste is empty.")
if size > MAX_BYTES: if size > MAX_BYTES:
raise HTTPException(413, "Paste is larger than 1 MiB.") raise too_big
if _rate_limited(client_ip(request)):
raise HTTPException(429, f"Too many pastes; the limit is {RATE_LIMIT} per hour.")
now = int(time.time()) now = int(time.time())
since = now - LIMIT_WINDOW
ip = _ip_hash(client_ip(request))
pid, token = secrets.token_urlsafe(6), secrets.token_urlsafe(18) pid, token = secrets.token_urlsafe(6), secrets.token_urlsafe(18)
with _lock, _db() as c: with _lock, _db() as c:
used = c.execute("SELECT COALESCE(SUM(size), 0) FROM pastes WHERE expires_at > ?", (now,)).fetchone()[0] if c.execute("SELECT COUNT(*) FROM creations WHERE ts > ? AND ip = ?", (since, ip)).fetchone()[0] >= PER_IP_LIMIT:
if used + size > MAX_TOTAL_BYTES: raise HTTPException(429, f"You've reached the limit of {PER_IP_LIMIT} pastes per 24 hours. Try again later.")
raise HTTPException(507, "The pastebin is full right now; 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( c.execute(
"INSERT INTO pastes (id, content, size, created_at, expires_at, delete_token) VALUES (?, ?, ?, ?, ?, ?)", "INSERT INTO pastes (id, content, size, created_at, expires_at, delete_token) VALUES (?, ?, ?, ?, ?, ?)",
(pid, content, size, now, now + TTL, token), (pid, content, size, now, now + TTL, token),