import os, json, time, hmac, hashlib, secrets, threading, logging, re, base64, datetime as dt from fastapi import FastAPI, HTTPException, Request, Depends from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel log = logging.getLogger("ember"); logging.basicConfig(level=logging.INFO) TOKEN = os.environ.get("HF_TOKEN"); REPO = os.environ.get("DATA_REPO", "Karandeeps40/ember-data") SECRET = (os.environ.get("SESSION_SECRET") or secrets.token_hex(32)).encode() LOCAL = os.environ.get("LOCAL_DB") # dev mode: local file instead of HF class Store: """Load-first, merge-before-write. Never writes remote unless a load succeeded (or repo genuinely empty).""" def __init__(s): s.lock = threading.RLock(); s.db = {"users": {}, "challenges": {}}; s.loaded = False; s.dirty = False; s.api = None def _fetch(s): if LOCAL: return json.load(open(LOCAL)) if os.path.exists(LOCAL) else {"users": {}, "challenges": {}} from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError s.api = s.api or HfApi(token=TOKEN) try: s.api.create_repo(REPO, repo_type="dataset", private=True, exist_ok=True) except Exception as e: log.warning("create_repo: %s", e) try: p = hf_hub_download(REPO, "db.json", repo_type="dataset", token=TOKEN, force_download=True) except EntryNotFoundError: return {"users": {}, "challenges": {}} # genuinely empty d = json.load(open(p)) if not isinstance(d, dict) or "users" not in d: raise ValueError("bad db shape") return d def load(s): if not TOKEN and not LOCAL: log.warning("no HF_TOKEN: memory only"); s.loaded = False; return try: remote = s._fetch() with s.lock: s.db = merge(remote, s.db); s.loaded = True log.info("loaded %d users", len(s.db["users"])) except Exception as e: log.error("load failed (keeping memory, no writes): %s", e); s.loaded = False def save(s): with s.lock: if not s.dirty: return if not s.loaded: s.load() if not s.loaded: return try: remote = s._fetch() # merge-before-write with s.lock: s.db = merge(remote, s.db); blob = json.dumps(s.db, separators=(",", ":")).encode(); s.dirty = False if LOCAL: open(LOCAL + ".tmp", "wb").write(blob); os.replace(LOCAL + ".tmp", LOCAL) else: s.api.upload_file(path_or_fileobj=blob, path_in_repo="db.json", repo_id=REPO, repo_type="dataset", commit_message="sync") except Exception as e: log.error("save failed, will retry: %s", e); s.dirty = True def loop(s): while True: time.sleep(20); s.save() def merge(a, b): """Merge two dbs; per-record newest 'u' (updated ms) wins, check-ins/friends unioned.""" out = {"users": dict(a.get("users", {})), "challenges": dict(a.get("challenges", {}))} for k, v in b.get("users", {}).items(): o = out["users"].get(k) if not o: out["users"][k] = v; continue w = v if v.get("u", 0) >= o.get("u", 0) else o; l = o if w is v else v w = json.loads(json.dumps(w)) w["friends"] = sorted(set(w.get("friends", [])) | set(l.get("friends", [])) - set(w.get("unfriended", []))) lh = {h["id"]: h for h in l.get("habits", [])} for h in w.get("habits", []): if h["id"] in lh and not h.get("deleted"): h["days"] = sorted(set(h.get("days", [])) | set(lh[h["id"]].get("days", [])) - set(h.get("undone", []))) ids = {h["id"] for h in w.get("habits", [])} w["habits"] += [h for h in l.get("habits", []) if h["id"] not in ids] seen = {(r["f"], r["t"]) for r in w.get("inbox", [])} w["inbox"] = (w.get("inbox", []) + [r for r in l.get("inbox", []) if (r["f"], r["t"]) not in seen])[-50:] out["users"][k] = w for k, v in b.get("challenges", {}).items(): o = out["challenges"].get(k) if not o: out["challenges"][k] = v; continue w = json.loads(json.dumps(v if v.get("u", 0) >= o.get("u", 0) else o)) w["members"] = sorted(set(o.get("members", [])) | set(v.get("members", [])) - set(w.get("left", []))) prog = {} for src in (o, v): for m, ds in src.get("prog", {}).items(): prog[m] = sorted(set(prog.get(m, [])) | set(ds)) w["prog"] = prog; out["challenges"][k] = w return out S = Store() app = FastAPI() @app.on_event("startup") def _start(): threading.Thread(target=S.load, daemon=True).start() threading.Thread(target=S.loop, daemon=True).start() def now(): return int(time.time() * 1000) def kdf(pw, salt): return hashlib.scrypt(pw.encode(), salt=bytes.fromhex(salt), n=2**15, r=8, p=1, maxmem=64 * 1024 * 1024, dklen=32).hex() def sign(u, ver): body = f"{u}.{ver}.{int(time.time()) + 90 * 86400}" return body + "." + hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:40] def me(req: Request): t = (req.headers.get("authorization") or "").removeprefix("Bearer ").strip() try: u, ver, exp, sig = t.rsplit(".", 3) ok = hmac.compare_digest(sig, hmac.new(SECRET, f"{u}.{ver}.{exp}".encode(), hashlib.sha256).hexdigest()[:40]) user = S.db["users"].get(u) if ok and int(exp) > time.time() and user and str(user.get("ver", 0)) == ver: return u except Exception: pass raise HTTPException(401, "Please sign in") def touch(u): S.db["users"][u]["u"] = now(); S.dirty = True def ymd(d): return dt.date.fromisoformat(d) def streak(days, kind="daily", n=1, today=None): if not days: return 0 today = today or dt.datetime.utcnow().date() + dt.timedelta(days=1) # tolerate timezones ahead of UTC ds = sorted({ymd(d) for d in days if re.match(r"^\d{4}-\d\d-\d\d$", d)}) if kind == "weekly": wk = {} for d in ds: k = d - dt.timedelta(days=d.weekday()); wk[k] = wk.get(k, 0) + 1 cur = today - dt.timedelta(days=today.weekday()); c = 0 if wk.get(cur, 0) < n: cur -= dt.timedelta(days=7) while wk.get(cur, 0) >= n: c += 1; cur -= dt.timedelta(days=7) return c s = set(ds); cur = max(ds) if (today - cur).days > 2: return 0 c = 0 while cur in s: c += 1; cur -= dt.timedelta(days=1) return c def best_streak(u): return max([streak(h.get("days", []), h.get("kind", "daily"), h.get("n", 1)) for h in u.get("habits", []) if not h.get("deleted")] or [0]) def week_count(u): cut = (dt.datetime.utcnow().date() - dt.timedelta(days=7)).isoformat() return sum(1 for h in u.get("habits", []) if not h.get("deleted") for d in h.get("days", []) if d > cut) def public(name): u = S.db["users"][name] return {"username": name, "display": u.get("display") or name, "avatar": u.get("avatar", "🔥"), "streak": best_streak(u), "week": week_count(u), "habits": [{"name": h["name"], "icon": h["icon"], "color": h["color"], "streak": streak(h.get("days", []), h.get("kind"), h.get("n", 1))} for h in u.get("habits", []) if not h.get("deleted") and not h.get("private")][:8]} def mine(name): u = S.db["users"][name] return {"username": name, "display": u.get("display") or name, "avatar": u.get("avatar", "🔥"), "invite": u["invite"], "habits": [h for h in u.get("habits", []) if not h.get("deleted")], "friends": [public(f) for f in u.get("friends", []) if f in S.db["users"]], "inbox": u.get("inbox", [])[-30:][::-1], "created": u.get("created"), "synced": S.loaded} class Cred(BaseModel): username: str; password: str; display: str | None = None; invite: str | None = None UN = re.compile(r"^[a-z0-9_.]{3,20}$") def befriend(a, b): if a == b: return for x, y in ((a, b), (b, a)): u = S.db["users"][x]; u.setdefault("friends", []) if y not in u["friends"]: u["friends"].append(y) u["unfriended"] = [z for z in u.get("unfriended", []) if z != y]; touch(x) def by_invite(code): code = (code or "").strip().upper() return next((k for k, v in S.db["users"].items() if v.get("invite") == code), None) _rl = {} def ratelimit(key, n=10, per=300): t = time.time(); q = [x for x in _rl.get(key, []) if t - x < per] if len(q) >= n: raise HTTPException(429, "Too many attempts. Try again in a few minutes.") q.append(t); _rl[key] = q @app.post("/api/signup") def signup(c: Cred, req: Request): ratelimit("su" + (req.client.host if req.client else ""), 8, 600) un = c.username.strip().lower() if not UN.match(un): raise HTTPException(400, "Username: 3–20 letters, numbers, _ or .") if len(c.password) < 8: raise HTTPException(400, "Password must be at least 8 characters") with S.lock: if un in S.db["users"]: raise HTTPException(409, "That username is taken") salt = secrets.token_hex(16) inv = secrets.token_hex(3).upper() while by_invite(inv): inv = secrets.token_hex(3).upper() S.db["users"][un] = {"salt": salt, "pw": kdf(c.password, salt), "ver": 1, "display": (c.display or un)[:30], "invite": inv, "created": now(), "habits": [], "friends": [], "inbox": [], "u": now()} f = by_invite(c.invite) if f: befriend(un, f) S.dirty = True threading.Thread(target=S.save, daemon=True).start() return {"token": sign(un, 1), "me": mine(un)} @app.post("/api/login") def login(c: Cred): un = c.username.strip().lower(); ratelimit("li" + un, 10, 300) u = S.db["users"].get(un) if not u or not hmac.compare_digest(u["pw"], kdf(c.password, u["salt"])): raise HTTPException(401, "Wrong username or password") if c.invite: f = by_invite(c.invite) if f: with S.lock: befriend(un, f) return {"token": sign(un, u.get("ver", 0)), "me": mine(un)} @app.get("/api/me") def get_me(u=Depends(me)): return mine(u) class Profile(BaseModel): display: str | None = None; avatar: str | None = None @app.post("/api/profile") def profile(p: Profile, u=Depends(me)): with S.lock: if p.display: S.db["users"][u]["display"] = p.display[:30] if p.avatar: S.db["users"][u]["avatar"] = p.avatar[:12] touch(u) return mine(u) class Habit(BaseModel): id: str | None = None; name: str; icon: str = "spark"; color: str = "#f5b94a"; kind: str = "daily"; n: int = 1; cat: str = "custom"; private: bool = False @app.post("/api/habits") def save_habit(h: Habit, u=Depends(me)): with S.lock: hs = S.db["users"][u]["habits"] if len([x for x in hs if not x.get("deleted")]) >= 30 and not h.id: raise HTTPException(400, "Habit limit reached") d = h.model_dump(); d["name"] = d["name"].strip()[:40] or "Habit"; d["n"] = max(1, min(7, d["n"])) d["kind"] = "weekly" if d["kind"] == "weekly" else "daily" if h.id: for x in hs: if x["id"] == h.id: x.update({k: v for k, v in d.items() if k != "id"}) else: d["id"] = secrets.token_hex(5); d["days"] = []; d["created"] = now(); hs.append(d) touch(u) return mine(u) @app.delete("/api/habits/{hid}") def del_habit(hid: str, u=Depends(me)): with S.lock: for x in S.db["users"][u]["habits"]: if x["id"] == hid: x["deleted"] = True touch(u) return mine(u) class Check(BaseModel): day: str; done: bool = True @app.post("/api/habits/{hid}/check") def check(hid: str, c: Check, u=Depends(me)): if not re.match(r"^\d{4}-\d\d-\d\d$", c.day): raise HTTPException(400, "bad day") if abs((ymd(c.day) - dt.datetime.utcnow().date()).days) > 400: raise HTTPException(400, "bad day") with S.lock: for x in S.db["users"][u]["habits"]: if x["id"] == hid: ds = set(x.get("days", [])); un = set(x.get("undone", [])) if c.done: ds.add(c.day); un.discard(c.day) else: ds.discard(c.day); un.add(c.day) x["days"] = sorted(ds); x["undone"] = sorted(un)[-60:] touch(u) return mine(u) class Code(BaseModel): code: str @app.post("/api/friends") def add_friend(c: Code, u=Depends(me)): code = c.code.strip() f = by_invite(code) or (code.lower().lstrip("@") if code.lower().lstrip("@") in S.db["users"] else None) if not f: raise HTTPException(404, "No one found with that code or username") if f == u: raise HTTPException(400, "That's you!") with S.lock: befriend(u, f) return mine(u) @app.delete("/api/friends/{f}") def unfriend(f: str, u=Depends(me)): with S.lock: for x, y in ((u, f), (f, u)): if x in S.db["users"]: d = S.db["users"][x]; d["friends"] = [z for z in d.get("friends", []) if z != y] d.setdefault("unfriended", []).append(y); touch(x) return mine(u) @app.get("/api/invite/{code}") def invite_info(code: str): f = by_invite(code) if not f: raise HTTPException(404, "Invite not found") p = public(f); return {"username": f, "display": p["display"], "avatar": p["avatar"], "streak": p["streak"]} class React(BaseModel): kind: str @app.post("/api/react/{f}") def react(f: str, r: React, u=Depends(me)): if f not in S.db["users"][u].get("friends", []): raise HTTPException(403, "Not friends") kind = r.kind if r.kind in ("cheer", "nudge", "fire", "clap") else "cheer" ratelimit(f"r{u}{f}", 6, 3600) with S.lock: S.db["users"][f].setdefault("inbox", []).append({"f": u, "k": kind, "t": now()}) S.db["users"][f]["inbox"] = S.db["users"][f]["inbox"][-50:]; touch(f) return {"ok": True} @app.post("/api/inbox/read") def inbox_read(u=Depends(me)): with S.lock: for m in S.db["users"][u].get("inbox", []): m["r"] = 1 touch(u) return {"ok": True} @app.get("/api/leaderboard") def leaderboard(u=Depends(me)): names = [u] + [f for f in S.db["users"][u].get("friends", []) if f in S.db["users"]] rows = [public(n) for n in names] rows.sort(key=lambda r: (-r["streak"], -r["week"])); return rows class Chal(BaseModel): title: str; icon: str = "trophy"; days: int = 30; color: str = "#f5b94a"; invite: list[str] = [] def chal_view(cid, u): c = S.db["challenges"][cid]; start = ymd(c["start"]); end = start + dt.timedelta(days=c["days"] - 1) ms = [{"username": m, "display": S.db["users"].get(m, {}).get("display", m), "avatar": S.db["users"].get(m, {}).get("avatar", "🔥"), "count": len(c.get("prog", {}).get(m, [])), "today": False} for m in c["members"]] ms.sort(key=lambda m: -m["count"]) return {**{k: c[k] for k in ("id", "title", "icon", "days", "color", "start", "owner")}, "end": end.isoformat(), "members": ms, "mine": c.get("prog", {}).get(u, []), "joined": u in c["members"]} @app.get("/api/challenges") def chals(u=Depends(me)): fr = set(S.db["users"][u].get("friends", [])) | {u} return [chal_view(k, u) for k, c in S.db["challenges"].items() if u in c["members"] or (c["owner"] in fr and u in c.get("invited", []))] @app.post("/api/challenges") def new_chal(c: Chal, u=Depends(me)): cid = secrets.token_hex(4) with S.lock: fr = set(S.db["users"][u].get("friends", [])) S.db["challenges"][cid] = {"id": cid, "title": c.title.strip()[:40] or "Challenge", "icon": c.icon[:12], "color": c.color, "days": max(3, min(100, c.days)), "start": dt.datetime.utcnow().date().isoformat(), "owner": u, "members": [u], "invited": [i for i in c.invite if i in fr], "prog": {}, "u": now()} S.dirty = True return chal_view(cid, u) @app.post("/api/challenges/{cid}/join") def join_chal(cid: str, u=Depends(me)): with S.lock: c = S.db["challenges"].get(cid) if not c: raise HTTPException(404, "Challenge not found") if u not in c["members"]: c["members"].append(u) c["left"] = [x for x in c.get("left", []) if x != u]; c["u"] = now(); S.dirty = True return chal_view(cid, u) @app.post("/api/challenges/{cid}/leave") def leave_chal(cid: str, u=Depends(me)): with S.lock: c = S.db["challenges"].get(cid) if c: c["members"] = [x for x in c["members"] if x != u]; c.setdefault("left", []).append(u); c["u"] = now(); S.dirty = True return {"ok": True} @app.post("/api/challenges/{cid}/check") def chal_check(cid: str, ch: Check, u=Depends(me)): with S.lock: c = S.db["challenges"].get(cid) if not c or u not in c["members"]: raise HTTPException(404, "Not in challenge") p = set(c.setdefault("prog", {}).get(u, [])) (p.add if ch.done else p.discard)(ch.day); c["prog"][u] = sorted(p); c["u"] = now(); S.dirty = True return chal_view(cid, u) class Pw(BaseModel): old: str; new: str @app.post("/api/password") def change_pw(p: Pw, u=Depends(me)): d = S.db["users"][u] if not hmac.compare_digest(d["pw"], kdf(p.old, d["salt"])): raise HTTPException(401, "Current password is wrong") if len(p.new) < 8: raise HTTPException(400, "Password must be at least 8 characters") with S.lock: d["salt"] = secrets.token_hex(16); d["pw"] = kdf(p.new, d["salt"]); d["ver"] = d.get("ver", 0) + 1; touch(u) return {"token": sign(u, d["ver"])} @app.get("/api/export") def export(u=Depends(me)): d = {k: v for k, v in S.db["users"][u].items() if k not in ("pw", "salt")}; return d @app.post("/api/delete_account") def delete_account(c: Cred, u=Depends(me)): d = S.db["users"][u] if c.username.lower() != u or not hmac.compare_digest(d["pw"], kdf(c.password, d["salt"])): raise HTTPException(401, "Wrong password") with S.lock: # tombstone (so merge doesn't resurrect), strip personal data S.db["users"][u] = {"deleted": True, "u": now() + 10**10, "salt": "00", "pw": "x", "ver": 999, "invite": "-", "habits": [], "friends": [], "inbox": []} for k, v in S.db["users"].items(): if u in v.get("friends", []): v["friends"].remove(u); v.setdefault("unfriended", []).append(u) S.dirty = True return {"ok": True} @app.get("/api/health") def health(): return {"ok": True, "loaded": S.loaded, "users": sum(1 for v in S.db["users"].values() if not v.get("deleted"))} ST = os.path.join(os.path.dirname(__file__), "static") @app.get("/sw.js") def sw(): return FileResponse(os.path.join(ST, "sw.js"), media_type="application/javascript", headers={"Cache-Control": "no-cache", "Service-Worker-Allowed": "/"}) @app.get("/manifest.webmanifest") def mf(): return FileResponse(os.path.join(ST, "manifest.webmanifest"), media_type="application/manifest+json") @app.get("/privacy") def privacy(): return FileResponse(os.path.join(ST, "privacy.html")) @app.get("/terms") def terms(): return FileResponse(os.path.join(ST, "terms.html")) app.mount("/static", StaticFiles(directory=ST), name="static") @app.get("/{path:path}") def spa(path: str): return FileResponse(os.path.join(ST, "index.html"), headers={"Cache-Control": "no-cache"})