File size: 2,256 Bytes
586216b 423e11a 586216b 423e11a 586216b 423e11a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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'<script src="/sand.js"></script>'
@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"</body>", TAG + b"</body>", 1) if b"</body>" 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")
|