import json, secrets, time, threading from fastapi import FastAPI, HTTPException, Request from fastapi.responses import Response from fastapi.staticfiles import StaticFiles app = FastAPI() DB = "/tmp/ghost_keys.json" lock = threading.Lock() TAG = b'' @app.middleware("http") async def sand_everywhere(request: Request, call_next): resp = await call_next(request) if resp.headers.get("content-type", "").startswith("text/html"): body = b"".join([c async for c in resp.body_iterator]) if TAG not in body: body = body.replace(b"", TAG + b"", 1) if b"" in body else body + TAG headers = {k: v for k, v in resp.headers.items() if k.lower() not in ("content-length", "etag")} return Response(body, status_code=resp.status_code, headers=headers, media_type="text/html") return resp def load(): try: with open(DB) as f: return json.load(f) except Exception: return {} def save(d): with open(DB, "w") as f: json.dump(d, f) def alive(rec): return rec and (rec["exp"] == 0 or rec["exp"] > time.time()) @app.post("/api/key") async def new_key(req: Request): b = await req.json() ttl = int(b.get("ttl", 0)); burn = bool(b.get("burn", False)) rid, key, owner = secrets.token_urlsafe(9), secrets.token_urlsafe(32), secrets.token_urlsafe(16) with lock: d = load() d[rid] = {"key": key, "owner": owner, "exp": time.time() + ttl if ttl else 0, "burn": burn, "t": time.time()} save(d) return {"id": rid, "key": key, "owner": owner} @app.get("/api/key/{rid}") def get_key(rid: str): with lock: d = load(); rec = d.get(rid) if not alive(rec): d.pop(rid, None); save(d) raise HTTPException(410, "ghosted") if rec["burn"]: d.pop(rid); save(d) return {"key": rec["key"]} @app.delete("/api/key/{rid}") def ghost(rid: str, owner: str): with lock: d = load(); rec = d.get(rid) if not rec or rec["owner"] != owner: raise HTTPException(403, "not yours") d.pop(rid); save(d) return {"ghosted": rid, "t": time.time()} app.mount("/", StaticFiles(directory=".", html=True), name="site")