Download server/app.py from ag235772/Workhub: direct link, hf CLI and curl.
- Browser
- Download file 13.6 kB
-
https://huggingface.co/spaces/ag235772/Workhub/resolve/main/server/app.py
- Command line
-
hf download hf://spaces/ag235772/Workhub/server/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ag235772/Workhub/resolve/main/server/app.py
13.6 kB
| """Work Hub auth + AI service. | |
| Serves the static web app and handles: Microsoft sign-in (@indusface.com only), device registration, | |
| TOTP two-factor, and an AI proxy. It never receives or stores the Excel work data. | |
| """ | |
| import os | |
| import re | |
| import secrets | |
| import time | |
| from collections import defaultdict, deque | |
| from datetime import date, timedelta | |
| from flask import Flask, abort, jsonify, make_response, redirect, request, send_from_directory, session | |
| from werkzeug.middleware.proxy_fix import ProxyFix | |
| import db | |
| import llm | |
| import security as sec | |
| BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| STATIC = os.path.join(BASE, "static") | |
| DEV_LOGIN = os.environ.get("DEV_LOGIN") == "1" # local testing only | |
| TENANT = os.environ.get("MS_TENANT_ID", "") | |
| CLIENT_ID = os.environ.get("MS_CLIENT_ID", "") | |
| CLIENT_SECRET = os.environ.get("MS_CLIENT_SECRET", "") | |
| BASE_URL = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/") | |
| COOKIE = "hub_device" | |
| app = Flask(__name__, static_folder=STATIC, static_url_path="/static") | |
| app.secret_key = sec.app_secret() | |
| app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1) | |
| app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax", | |
| SESSION_COOKIE_SECURE=BASE_URL.startswith("https"), | |
| PERMANENT_SESSION_LIFETIME=timedelta(hours=10), MAX_CONTENT_LENGTH=2_000_000) | |
| db.init() | |
| if os.environ.get("SPACE_ID") and not os.environ.get("APP_SECRET"): | |
| print("WARNING: APP_SECRET is not set - sessions and 2FA secrets will be lost on every restart. Set it in Space secrets.", flush=True) | |
| def healthz(): | |
| return "ok" | |
| # ------------------------------------------------------------------ helpers | |
| def ip(): | |
| return request.remote_addr or "" | |
| def device_from_cookie(): | |
| t = request.cookies.get(COOKIE) | |
| if not t: | |
| return None | |
| return db.q1("SELECT * FROM devices WHERE token_hash=? AND revoked=0", sec.hash_token(t)) | |
| def ua_label(): | |
| ua = request.headers.get("User-Agent", "") | |
| br = next((n for p, n in (("Edg/", "Edge"), ("Chrome/", "Chrome"), ("Firefox/", "Firefox"), ("Safari/", "Safari")) if p in ua), "Browser") | |
| os_ = next((n for p, n in (("Windows", "Windows"), ("Mac OS", "macOS"), ("Linux", "Linux"), ("Android", "Android"), ("iPhone", "iOS")) if p in ua), "device") | |
| return f"{br} on {os_}" | |
| def user(): | |
| uid = session.get("uid") | |
| return db.q1("SELECT * FROM users WHERE id=?", uid) if uid else None | |
| def ready(): | |
| u = user() | |
| return u if (u and session.get("stage") == "ready") else None | |
| def need_ready(): | |
| u = ready() | |
| if not u: | |
| abort(401) | |
| return u | |
| def need_json(): | |
| if request.method in ("POST", "PUT", "DELETE") and not request.is_json: | |
| abort(415) # forces a CORS preflight for cross-site callers -> basic CSRF protection | |
| def register_device(u, resp): | |
| tok = sec.new_device_token() | |
| db.ex("INSERT INTO devices(user_id,token_hash,label,created,last_seen) VALUES(?,?,?,?,?)", | |
| u["id"], sec.hash_token(tok), ua_label(), time.time(), time.time()) | |
| resp.set_cookie(COOKIE, tok, max_age=400 * 86400, httponly=True, samesite="Lax", | |
| secure=BASE_URL.startswith("https")) | |
| db.audit(u["email"], "device_registered", ip(), ua_label()) | |
| def headers(r): | |
| r.headers["Content-Security-Policy"] = ("default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; " | |
| "script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'") | |
| r.headers["X-Content-Type-Options"] = "nosniff" | |
| r.headers["Referrer-Policy"] = "no-referrer" | |
| if BASE_URL.startswith("https"): | |
| r.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains" | |
| if request.path.startswith("/api/") or request.path.startswith("/auth/"): | |
| r.headers["Cache-Control"] = "no-store" | |
| return r | |
| def _401(e): | |
| return jsonify(error="Please sign in."), 401 | |
| def _415(e): | |
| return jsonify(error="JSON required."), 415 | |
| # ------------------------------------------------------------------ pages | |
| def index(): | |
| return send_from_directory(STATIC, "index.html") | |
| def state(): | |
| u = user() | |
| dev = device_from_cookie() | |
| out = {"stage": session.get("stage", "anon") if u else "anon", "ai": llm.available(), "domain": sec.ALLOWED_DOMAIN, | |
| "ms_configured": bool(TENANT and CLIENT_ID and CLIENT_SECRET), "dev_login": DEV_LOGIN} | |
| if u: | |
| out.update(email=u["email"], name=u["name"]) | |
| if dev: | |
| owner = db.q1("SELECT email FROM users WHERE id=?", dev["user_id"]) | |
| out["device"] = {"known": True, "hint": sec.mask_email(owner["email"]) if owner else ""} | |
| else: | |
| out["device"] = {"known": False, "hint": ""} | |
| return jsonify(out) | |
| # ------------------------------------------------------------------ Microsoft sign-in | |
| def _msal(): | |
| import msal | |
| return msal.ConfidentialClientApplication(CLIENT_ID, authority=f"https://login.microsoftonline.com/{TENANT}", | |
| client_credential=CLIENT_SECRET) | |
| def auth_login(): | |
| if DEV_LOGIN and request.host.split(":")[0] in ("localhost", "127.0.0.1"): | |
| return redirect("/auth/dev") | |
| if not (TENANT and CLIENT_ID and CLIENT_SECRET): | |
| return "Microsoft sign-in is not configured on the server (MS_TENANT_ID / MS_CLIENT_ID / MS_CLIENT_SECRET).", 503 | |
| flow = _msal().initiate_auth_code_flow(["User.Read"], redirect_uri=BASE_URL + "/auth/callback", | |
| domain_hint=sec.ALLOWED_DOMAIN) | |
| session["flow"] = flow | |
| return redirect(flow["auth_uri"]) | |
| def auth_callback(): | |
| flow = session.pop("flow", None) | |
| if not flow: | |
| return redirect("/") | |
| try: | |
| res = _msal().acquire_token_by_auth_code_flow(flow, request.args) | |
| except ValueError: | |
| return redirect("/") | |
| if "error" in res: | |
| db.audit("", "ms_login_error", ip(), res.get("error", "")) | |
| return redirect("/?auth_error=1") | |
| c = res.get("id_token_claims", {}) | |
| email = (c.get("preferred_username") or c.get("email") or c.get("upn") or "").lower() | |
| if TENANT and c.get("tid") and c["tid"].lower() != TENANT.lower() and TENANT.lower() not in ("common", "organizations"): | |
| return redirect("/?auth_error=tenant") | |
| return _after_ms(email, c.get("name") or email) | |
| def _after_ms(email, name): | |
| """Called once Microsoft (or dev login) has proven the identity.""" | |
| email = (email or "").lower() | |
| if not sec.allowed_email(email): | |
| db.audit(email, "rejected_domain", ip()) | |
| session.clear() | |
| return redirect("/?auth_error=domain") | |
| u = db.q1("SELECT * FROM users WHERE email=?", email) | |
| if not u: | |
| db.ex("INSERT INTO users(email,name,created) VALUES(?,?,?)", email, name, time.time()) | |
| u = db.q1("SELECT * FROM users WHERE email=?", email) | |
| dev = device_from_cookie() | |
| if dev and dev["user_id"] != u["id"]: | |
| session.clear() | |
| return redirect("/?auth_error=device_owner") | |
| session.clear() | |
| session.permanent = True | |
| session["uid"] = u["id"] | |
| db.ex("UPDATE users SET last_login=?, name=COALESCE(?,name) WHERE id=?", time.time(), name, u["id"]) | |
| if not u["totp_confirmed"]: | |
| session["stage"] = "enroll" | |
| elif dev: | |
| session["stage"] = "ready" | |
| db.ex("UPDATE devices SET last_seen=? WHERE id=?", time.time(), dev["id"]) | |
| db.audit(email, "login_known_device", ip()) | |
| else: | |
| session["stage"] = "otp" | |
| return redirect("/") | |
| def auth_dev(): | |
| if not (DEV_LOGIN and request.host.split(":")[0] in ("localhost", "127.0.0.1")): | |
| abort(404) | |
| if request.method == "POST": | |
| return _after_ms(request.form.get("email", ""), request.form.get("email", "").split("@")[0]) | |
| return ('<form method="post" style="font:16px system-ui;margin:60px auto;max-width:360px">' | |
| '<h3>DEV login (simulates Microsoft)</h3><input name="email" placeholder="name@indusface.com" ' | |
| 'style="width:100%;padding:8px"><button style="margin-top:10px;padding:8px 16px">Continue</button></form>') | |
| # ------------------------------------------------------------------ 2FA | |
| def _locked(u): | |
| return u["locked_until"] and u["locked_until"] > time.time() | |
| def _check_code(u, code): | |
| if _locked(u): | |
| return None, ("Too many wrong codes. Try again in a few minutes.", 429) | |
| step = sec.verify_totp(sec.decrypt(u["totp_secret"]), code, u["last_step"] or 0) | |
| if step is None: | |
| fails = (u["fail_count"] or 0) + 1 | |
| lock = time.time() + 900 if fails >= 5 else 0 | |
| db.ex("UPDATE users SET fail_count=?, locked_until=? WHERE id=?", 0 if lock else fails, lock, u["id"]) | |
| db.audit(u["email"], "otp_fail", ip()) | |
| return None, ("That code is not correct.", 400) | |
| db.ex("UPDATE users SET fail_count=0, locked_until=0, last_step=? WHERE id=?", step, u["id"]) | |
| return step, None | |
| def enroll_start(): | |
| need_json() | |
| u = user() | |
| if not u or session.get("stage") != "enroll": | |
| abort(401) | |
| if not u["totp_secret"]: | |
| db.ex("UPDATE users SET totp_secret=? WHERE id=?", sec.encrypt(sec.new_totp_secret()), u["id"]) | |
| u = user() | |
| secret = sec.decrypt(u["totp_secret"]) | |
| return jsonify(qr=sec.qr_data_uri(sec.totp_uri(secret, u["email"])), secret=secret, issuer=sec.ISSUER) | |
| def enroll_verify(): | |
| need_json() | |
| u = user() | |
| if not u or session.get("stage") != "enroll" or not u["totp_secret"]: | |
| abort(401) | |
| step, err = _check_code(u, (request.get_json() or {}).get("code")) | |
| if err: | |
| return jsonify(error=err[0]), err[1] | |
| db.ex("UPDATE users SET totp_confirmed=1 WHERE id=?", u["id"]) | |
| session["stage"] = "ready" | |
| resp = make_response(jsonify(ok=True)) | |
| if not device_from_cookie(): | |
| register_device(u, resp) | |
| db.audit(u["email"], "registered", ip()) | |
| return resp | |
| def otp(): | |
| need_json() | |
| u = user() | |
| if not u or session.get("stage") != "otp": | |
| abort(401) | |
| step, err = _check_code(u, (request.get_json() or {}).get("code")) | |
| if err: | |
| return jsonify(error=err[0]), err[1] | |
| session["stage"] = "ready" | |
| resp = make_response(jsonify(ok=True)) | |
| register_device(u, resp) | |
| return resp | |
| def logout(): | |
| need_json() | |
| session.clear() | |
| return jsonify(ok=True) | |
| # ------------------------------------------------------------------ devices | |
| def devices(): | |
| u = need_ready() | |
| cur = device_from_cookie() | |
| rows = db.qa("SELECT id,label,created,last_seen FROM devices WHERE user_id=? AND revoked=0 ORDER BY last_seen DESC", u["id"]) | |
| return jsonify(devices=[{**dict(r), "current": bool(cur and cur["id"] == r["id"])} for r in rows]) | |
| def revoke(did): | |
| need_json() | |
| u = need_ready() | |
| cur = device_from_cookie() | |
| if cur and cur["id"] == did: | |
| return jsonify(error="You can't remove the device you're using."), 400 | |
| db.ex("UPDATE devices SET revoked=1 WHERE id=? AND user_id=?", did, u["id"]) | |
| db.audit(u["email"], "device_revoked", ip(), str(did)) | |
| return jsonify(ok=True) | |
| # ------------------------------------------------------------------ AI proxy (stateless) | |
| _hits = defaultdict(deque) | |
| def ai_gate(): | |
| need_json() | |
| u = need_ready() | |
| if not llm.available(): | |
| return None, (jsonify(error="AI is not enabled on this server.", ai=False), 503) | |
| q = _hits[u["id"]] | |
| now = time.time() | |
| while q and q[0] < now - 60: | |
| q.popleft() | |
| if len(q) >= 30: | |
| return None, (jsonify(error="Slow down a little – too many AI requests."), 429) | |
| q.append(now) | |
| return u, None | |
| def _ai(fn): | |
| u, err = ai_gate() | |
| if err: | |
| return err | |
| try: | |
| return jsonify(result=fn(request.get_json() or {})) | |
| except Exception as e: # never leak provider details/payloads | |
| db.audit(u["email"], "ai_error", ip(), type(e).__name__) | |
| return jsonify(error="The AI service could not complete that request."), 502 | |
| def ai_spec(): | |
| return _ai(lambda d: llm.nl_to_spec(str(d.get("question", ""))[:500], date.today().isoformat())) | |
| def ai_mail(): | |
| def go(d): | |
| cands = [{"title": str(t.get("title", ""))[:200], "body": str(t.get("body", ""))[:6000]} for t in (d.get("templates") or [])[:3]] | |
| return llm.mail("fix" if d.get("mode") == "fix" else "draft", str(d.get("text", ""))[:8000], cands) | |
| return _ai(go) | |
| def ai_import_map(): | |
| return _ai(lambda d: llm.import_map((d.get("rows") or [])[:15], date.today().isoformat())) | |
| def ai_import_extract(): | |
| def go(d): | |
| items = [{"i": int(x["i"]), "text": str(x["text"])[:1500]} for x in (d.get("items") or [])[:30]] | |
| return llm.import_extract(items, date.today().isoformat()) | |
| return _ai(go) | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", "5000")) | |
| print(f"Work Hub on {BASE_URL} (dev login: {'ON' if DEV_LOGIN else 'off'}, AI: {'on' if llm.available() else 'off'})") | |
| app.run(host=os.environ.get("HOST", "127.0.0.1"), port=port) | |