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:
parent
792d48553c
commit
f4232ef9b5
3 changed files with 50 additions and 36 deletions
|
|
@ -55,7 +55,9 @@ on the same host in front of it.
|
|||
|
||||
## 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
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
// 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).
|
||||
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() {
|
||||
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 updateInfo = () => {
|
||||
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);
|
||||
};
|
||||
ta.addEventListener('input', () => {
|
||||
|
|
@ -65,9 +65,17 @@ function renderCreate(root, ctx, timers) {
|
|||
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() {
|
||||
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;
|
||||
const p = await createPaste(ta.value);
|
||||
btn.disabled = false;
|
||||
|
|
@ -102,8 +110,9 @@ function renderCreate(root, ctx, timers) {
|
|||
|
||||
root.append(
|
||||
el('div.tool.paste-tool', {},
|
||||
el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info, 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.'), list),
|
||||
el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info,
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -2,34 +2,37 @@
|
|||
|
||||
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, 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 hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
TTL = 24 * 3600
|
||||
MAX_BYTES = 1024 * 1024 # per paste
|
||||
MAX_TOTAL_BYTES = 256 * 1024 * 1024 # all live pastes together
|
||||
RATE_LIMIT = 30 # creations per IP ...
|
||||
RATE_WINDOW = 3600 # ... per this many seconds
|
||||
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()
|
||||
_recent: dict[str, deque] = defaultdict(deque)
|
||||
_ip_key = b""
|
||||
_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 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:
|
||||
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():
|
||||
|
|
@ -84,19 +95,8 @@ def client_ip(request: Request) -> str:
|
|||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
def _rate_limited(ip: str) -> bool:
|
||||
now = time.monotonic()
|
||||
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 _ip_hash(ip: str) -> str:
|
||||
return hmac.new(_ip_key, ip.encode(), hashlib.sha256).hexdigest()[:32]
|
||||
|
||||
|
||||
def _get(pid: str) -> sqlite3.Row:
|
||||
|
|
@ -112,11 +112,12 @@ def _get(pid: str) -> sqlite3.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) > MAX_BYTES + 64 * 1024:
|
||||
raise HTTPException(413, "Paste is larger than 1 MiB.")
|
||||
if len(body) > 2 * MAX_BYTES + 64 * 1024: # room for JSON escaping (\n, \", …)
|
||||
raise too_big
|
||||
try:
|
||||
data = json.loads(body)
|
||||
content = data["content"]
|
||||
|
|
@ -127,16 +128,18 @@ async def create(request: Request):
|
|||
if not content.strip():
|
||||
raise HTTPException(400, "Paste is empty.")
|
||||
if size > MAX_BYTES:
|
||||
raise HTTPException(413, "Paste is larger than 1 MiB.")
|
||||
if _rate_limited(client_ip(request)):
|
||||
raise HTTPException(429, f"Too many pastes; the limit is {RATE_LIMIT} per hour.")
|
||||
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:
|
||||
used = c.execute("SELECT COALESCE(SUM(size), 0) FROM pastes WHERE expires_at > ?", (now,)).fetchone()[0]
|
||||
if used + size > MAX_TOTAL_BYTES:
|
||||
raise HTTPException(507, "The pastebin is full right now; try again later.")
|
||||
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),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue