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/; 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 and text content at .txt; upload_dir holds binary uploads at .; 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/; atomic: write to .tmp. 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/.txt" method read_content(paste_id: str) -> str | None: desc "content of store_dir/.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/. and return the saved path as stored (absolute)" method delete(paste_id: str) -> None: desc "remove the metadata file, the .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 .tmp.* files left by a crashed write (old app never cleaned those — fixed); skip .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=) 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/', raw: '/pastes//raw', download: '/pastes//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)