Spaces:
Running
Running
feat: add account, authentication, database, ratelimit, and webhook services for flmcp
Browse files- app/services/flmcp/accounts.py +52 -0
- app/services/flmcp/auth.py +67 -0
- app/services/flmcp/db.py +13 -0
- app/services/flmcp/ratelimit.py +53 -0
- app/services/flmcp/webhooks.py +69 -0
app/services/flmcp/accounts.py
CHANGED
|
@@ -220,3 +220,55 @@ def devices(conn: Any, license_id: str) -> list[dict]:
|
|
| 220 |
for r in rows
|
| 221 |
]
|
| 222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
for r in rows
|
| 221 |
]
|
| 222 |
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# Throwaway-mailbox domains that must not receive a free trial.
|
| 226 |
+
DISPOSABLE_DOMAINS = frozenset(
|
| 227 |
+
"mailinator.com guerrillamail.com 10minutemail.com tempmail.com temp-mail.org yopmail.com "
|
| 228 |
+
"trashmail.com sharklasers.com getnada.com dispostable.com maildrop.cc throwawaymail.com "
|
| 229 |
+
"fakeinbox.com mintemail.com mohmal.com emailondeck.com".split()
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def account_for_user(conn: Any, auth_user_id: str, email: str, now: int) -> str:
|
| 234 |
+
"""The account of a signed-in Google user. Linked by the verified email, so a licence a
|
| 235 |
+
payment provider created for that address is found; the Supabase id is then pinned to it."""
|
| 236 |
+
email = email.strip().lower()
|
| 237 |
+
row = conn.execute("SELECT id FROM accounts WHERE auth_user_id=?", (auth_user_id,)).fetchone()
|
| 238 |
+
if row:
|
| 239 |
+
return row["id"]
|
| 240 |
+
row = conn.execute("SELECT id, auth_user_id FROM accounts WHERE email=?", (email,)).fetchone()
|
| 241 |
+
if row:
|
| 242 |
+
if row["auth_user_id"] and row["auth_user_id"] != auth_user_id:
|
| 243 |
+
raise ApiError(409, "account_conflict", "this email belongs to another sign-in")
|
| 244 |
+
conn.execute("UPDATE accounts SET auth_user_id=? WHERE id=?", (auth_user_id, row["id"]))
|
| 245 |
+
return row["id"]
|
| 246 |
+
aid = uuid.uuid4().hex
|
| 247 |
+
conn.execute(
|
| 248 |
+
"INSERT INTO accounts(id, email, auth_user_id, created_at) VALUES (?,?,?,?)",
|
| 249 |
+
(aid, email, auth_user_id, now),
|
| 250 |
+
)
|
| 251 |
+
return aid
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def latest_license(conn: Any, account_id: str) -> Any:
|
| 255 |
+
return conn.execute(
|
| 256 |
+
"SELECT * FROM licenses WHERE account_id=? AND status IN ('active','past_due','canceled')"
|
| 257 |
+
" ORDER BY (plan='trial'), created_at DESC LIMIT 1",
|
| 258 |
+
(account_id,),
|
| 259 |
+
).fetchone()
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def trial_used(conn: Any, account_id: str) -> bool:
|
| 263 |
+
row = conn.execute(
|
| 264 |
+
"SELECT 1 AS x FROM licenses WHERE account_id=? AND plan='trial'", (account_id,)
|
| 265 |
+
).fetchone()
|
| 266 |
+
return row is not None
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def rotate_key(conn: Any, license_id: str) -> str:
|
| 270 |
+
"""Replace the licence key (leaked or lost). The new key is returned once; only its hash is
|
| 271 |
+
stored. Devices already activated keep working; new activations need the new key."""
|
| 272 |
+
key = keys.new_key()
|
| 273 |
+
conn.execute("UPDATE licenses SET key_hash=? WHERE id=?", (keys.hash_key(key), license_id))
|
| 274 |
+
return key
|
app/services/flmcp/auth.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Supabase Auth (Google sign-in) token verification for the FL-MCP dashboard.
|
| 2 |
+
|
| 3 |
+
The browser signs in with Supabase and sends its access token as a Bearer header. The token is
|
| 4 |
+
verified here against the project's public JWKS (asymmetric keys), so no secret is needed.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from functools import lru_cache
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import jwt
|
| 15 |
+
from jwt import PyJWKClient
|
| 16 |
+
|
| 17 |
+
from .errors import ApiError
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass(frozen=True)
|
| 21 |
+
class AuthUser:
|
| 22 |
+
id: str
|
| 23 |
+
email: str
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _supabase_url() -> str:
|
| 27 |
+
return os.environ.get("SUPABASE_URL", "").rstrip("/")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@lru_cache(maxsize=1)
|
| 31 |
+
def _jwks_client() -> PyJWKClient:
|
| 32 |
+
url = os.environ.get("SUPABASE_JWKS_URL") or f"{_supabase_url()}/auth/v1/.well-known/jwks.json"
|
| 33 |
+
return PyJWKClient(url, cache_keys=True, lifespan=3600)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _signing_key(token: str) -> Any:
|
| 37 |
+
"""Separate function so tests can swap the key source."""
|
| 38 |
+
return _jwks_client().get_signing_key_from_jwt(token).key
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def verify_token(token: str) -> AuthUser:
|
| 42 |
+
base = _supabase_url()
|
| 43 |
+
if not base:
|
| 44 |
+
raise ApiError(503, "auth_unconfigured", "sign-in is not configured on the server")
|
| 45 |
+
try:
|
| 46 |
+
claims = jwt.decode(
|
| 47 |
+
token,
|
| 48 |
+
_signing_key(token),
|
| 49 |
+
algorithms=["ES256", "RS256"],
|
| 50 |
+
audience="authenticated",
|
| 51 |
+
issuer=f"{base}/auth/v1",
|
| 52 |
+
options={"require": ["exp", "sub", "iss", "aud"]},
|
| 53 |
+
)
|
| 54 |
+
except Exception: # expired, bad signature, wrong issuer, JWKS unreachable
|
| 55 |
+
raise ApiError(401, "invalid_session", "your session is invalid or expired; sign in again") from None
|
| 56 |
+
email = str(claims.get("email") or "").strip().lower()
|
| 57 |
+
meta = claims.get("user_metadata") or {}
|
| 58 |
+
if not email or "@" not in email or meta.get("email_verified") is False:
|
| 59 |
+
raise ApiError(403, "email_unverified", "a verified email address is required")
|
| 60 |
+
return AuthUser(id=str(claims["sub"]), email=email)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def bearer_user(authorization: str | None) -> AuthUser:
|
| 64 |
+
scheme, _, token = (authorization or "").partition(" ")
|
| 65 |
+
if scheme.lower() != "bearer" or not token.strip():
|
| 66 |
+
raise ApiError(401, "invalid_session", "sign in to continue")
|
| 67 |
+
return verify_token(token.strip())
|
app/services/flmcp/db.py
CHANGED
|
@@ -21,6 +21,7 @@ SQLITE_SCHEMA = """
|
|
| 21 |
CREATE TABLE IF NOT EXISTS accounts (
|
| 22 |
id TEXT PRIMARY KEY,
|
| 23 |
email TEXT NOT NULL UNIQUE,
|
|
|
|
| 24 |
created_at INTEGER NOT NULL
|
| 25 |
);
|
| 26 |
|
|
@@ -116,6 +117,7 @@ PG_SCHEMA = """
|
|
| 116 |
CREATE TABLE IF NOT EXISTS accounts (
|
| 117 |
id TEXT PRIMARY KEY,
|
| 118 |
email TEXT NOT NULL UNIQUE,
|
|
|
|
| 119 |
created_at BIGINT NOT NULL
|
| 120 |
);
|
| 121 |
|
|
@@ -318,6 +320,13 @@ class DB:
|
|
| 318 |
try:
|
| 319 |
conn.execute("PRAGMA journal_mode=WAL")
|
| 320 |
conn.executescript(SQLITE_SCHEMA)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
finally:
|
| 322 |
conn.close()
|
| 323 |
|
|
@@ -327,6 +336,10 @@ class DB:
|
|
| 327 |
try:
|
| 328 |
with conn.cursor() as cur:
|
| 329 |
cur.execute(PG_SCHEMA)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
conn.commit()
|
| 331 |
finally:
|
| 332 |
conn.close()
|
|
|
|
| 21 |
CREATE TABLE IF NOT EXISTS accounts (
|
| 22 |
id TEXT PRIMARY KEY,
|
| 23 |
email TEXT NOT NULL UNIQUE,
|
| 24 |
+
auth_user_id TEXT UNIQUE,
|
| 25 |
created_at INTEGER NOT NULL
|
| 26 |
);
|
| 27 |
|
|
|
|
| 117 |
CREATE TABLE IF NOT EXISTS accounts (
|
| 118 |
id TEXT PRIMARY KEY,
|
| 119 |
email TEXT NOT NULL UNIQUE,
|
| 120 |
+
auth_user_id TEXT UNIQUE,
|
| 121 |
created_at BIGINT NOT NULL
|
| 122 |
);
|
| 123 |
|
|
|
|
| 320 |
try:
|
| 321 |
conn.execute("PRAGMA journal_mode=WAL")
|
| 322 |
conn.executescript(SQLITE_SCHEMA)
|
| 323 |
+
cols = [r[1] for r in conn.execute("PRAGMA table_info(accounts)")]
|
| 324 |
+
if "auth_user_id" not in cols: # database created before sign-in existed
|
| 325 |
+
conn.execute("ALTER TABLE accounts ADD COLUMN auth_user_id TEXT")
|
| 326 |
+
conn.execute(
|
| 327 |
+
"CREATE UNIQUE INDEX IF NOT EXISTS accounts_auth ON accounts(auth_user_id)"
|
| 328 |
+
)
|
| 329 |
+
conn.commit()
|
| 330 |
finally:
|
| 331 |
conn.close()
|
| 332 |
|
|
|
|
| 336 |
try:
|
| 337 |
with conn.cursor() as cur:
|
| 338 |
cur.execute(PG_SCHEMA)
|
| 339 |
+
cur.execute("ALTER TABLE accounts ADD COLUMN IF NOT EXISTS auth_user_id TEXT")
|
| 340 |
+
cur.execute(
|
| 341 |
+
"CREATE UNIQUE INDEX IF NOT EXISTS accounts_auth ON accounts(auth_user_id)"
|
| 342 |
+
)
|
| 343 |
conn.commit()
|
| 344 |
finally:
|
| 345 |
conn.close()
|
app/services/flmcp/ratelimit.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sliding-window rate limiter for the licence API.
|
| 2 |
+
|
| 3 |
+
In memory, per process: the Space runs a single instance, so this is enough to stop spam and
|
| 4 |
+
brute force. If the service is ever scaled out, move the counters to Postgres or Redis.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import threading
|
| 10 |
+
import time
|
| 11 |
+
from collections import defaultdict, deque
|
| 12 |
+
|
| 13 |
+
from .errors import ApiError
|
| 14 |
+
|
| 15 |
+
_lock = threading.Lock()
|
| 16 |
+
_hits: dict[str, deque[float]] = defaultdict(deque)
|
| 17 |
+
_MAX_KEYS = 50_000
|
| 18 |
+
|
| 19 |
+
# bucket -> (max requests, window seconds)
|
| 20 |
+
LIMITS: dict[str, tuple[int, int]] = {
|
| 21 |
+
"activate_ip": (10, 60),
|
| 22 |
+
"activate_key": (10, 300),
|
| 23 |
+
"account_token": (60, 60),
|
| 24 |
+
"reserve_token": (60, 60),
|
| 25 |
+
"me_user": (60, 60),
|
| 26 |
+
"trial_ip": (3, 3600),
|
| 27 |
+
"trial_user": (3, 3600),
|
| 28 |
+
"rotate_user": (5, 3600),
|
| 29 |
+
"webhook_ip": (120, 60),
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def hit(bucket: str, key: str, now: float | None = None) -> None:
|
| 34 |
+
"""Count one request; raise 429 with Retry-After when the bucket is full."""
|
| 35 |
+
limit, window = LIMITS[bucket]
|
| 36 |
+
t = time.monotonic() if now is None else now
|
| 37 |
+
name = f"{bucket}:{key}"
|
| 38 |
+
with _lock:
|
| 39 |
+
if len(_hits) > _MAX_KEYS:
|
| 40 |
+
for stale in [k for k, q in _hits.items() if not q or q[-1] < t - 3600]:
|
| 41 |
+
del _hits[stale]
|
| 42 |
+
q = _hits[name]
|
| 43 |
+
while q and q[0] <= t - window:
|
| 44 |
+
q.popleft()
|
| 45 |
+
if len(q) >= limit:
|
| 46 |
+
retry = max(1, int(window - (t - q[0])))
|
| 47 |
+
raise ApiError(429, "rate_limited", "too many requests; slow down", retry_after=retry)
|
| 48 |
+
q.append(t)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reset() -> None:
|
| 52 |
+
with _lock:
|
| 53 |
+
_hits.clear()
|
app/services/flmcp/webhooks.py
CHANGED
|
@@ -155,3 +155,72 @@ def apply(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
|
|
| 155 |
return {"duplicate": True}
|
| 156 |
return handler(conn, provider, ev, now, cfg)
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
return {"duplicate": True}
|
| 156 |
return handler(conn, provider, ev, now, cfg)
|
| 157 |
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
# ── Lemon Squeezy adapter ─────────────────────────────────────────────
|
| 161 |
+
# Lemon Squeezy signs the raw body with HMAC-SHA256 (hex, header X-Signature) and sends
|
| 162 |
+
# {"meta": {"event_name": ...}, "data": {"id": ..., "attributes": {...}}}. Variant ids are mapped
|
| 163 |
+
# to plans or credit packs with FLMCP_LS_VARIANTS="<variant_id>=pro,<variant_id>=pack_100".
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _ts(value: Any) -> int | None:
|
| 167 |
+
from datetime import datetime
|
| 168 |
+
|
| 169 |
+
if not isinstance(value, str) or not value:
|
| 170 |
+
return None
|
| 171 |
+
try:
|
| 172 |
+
return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp())
|
| 173 |
+
except ValueError:
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def normalize_lemonsqueezy(payload: dict, variants: dict[str, str], cfg: Config) -> dict | None:
|
| 178 |
+
"""Translate one Lemon Squeezy event into this module's event format; None means 'not for us'."""
|
| 179 |
+
meta = payload.get("meta") or {}
|
| 180 |
+
data = payload.get("data") or {}
|
| 181 |
+
attrs = data.get("attributes") or {}
|
| 182 |
+
name = str(meta.get("event_name") or "")
|
| 183 |
+
did = str(data.get("id") or "")
|
| 184 |
+
stamp = str(attrs.get("updated_at") or attrs.get("created_at") or "")
|
| 185 |
+
if not name or not did:
|
| 186 |
+
return None
|
| 187 |
+
event_id = f"{name}:{did}:{stamp}"
|
| 188 |
+
created = _ts(attrs.get("created_at"))
|
| 189 |
+
|
| 190 |
+
if name == "order_created":
|
| 191 |
+
item = attrs.get("first_order_item") or {}
|
| 192 |
+
target = variants.get(str(item.get("variant_id") or ""))
|
| 193 |
+
if target not in cfg.packs or attrs.get("status") != "paid":
|
| 194 |
+
return None # subscription orders are handled through subscription_* events
|
| 195 |
+
return {"id": event_id, "type": "topup.paid", "email": attrs.get("user_email"), "pack": target}
|
| 196 |
+
|
| 197 |
+
plan = variants.get(str(attrs.get("variant_id") or ""))
|
| 198 |
+
if name == "subscription_created":
|
| 199 |
+
if plan not in cfg.plans:
|
| 200 |
+
raise ApiError(400, "unknown_variant", "variant is not mapped to a plan")
|
| 201 |
+
start = created or 0
|
| 202 |
+
end = _ts(attrs.get("renews_at")) or start + 31 * 86400
|
| 203 |
+
return {
|
| 204 |
+
"id": event_id, "type": "subscription.started", "email": attrs.get("user_email"),
|
| 205 |
+
"plan": plan, "ref": did, "period_start": start, "period_end": end,
|
| 206 |
+
} # fmt: skip
|
| 207 |
+
if name == "subscription_payment_success":
|
| 208 |
+
if attrs.get("billing_reason") != "renewal":
|
| 209 |
+
return None
|
| 210 |
+
start = created or 0
|
| 211 |
+
return {
|
| 212 |
+
"id": event_id, "type": "subscription.renewed", "ref": str(attrs.get("subscription_id")),
|
| 213 |
+
"period_start": start, "period_end": start + 31 * 86400,
|
| 214 |
+
} # fmt: skip
|
| 215 |
+
if name == "subscription_updated":
|
| 216 |
+
status = attrs.get("status")
|
| 217 |
+
if status == "past_due":
|
| 218 |
+
return {"id": event_id, "type": "subscription.past_due", "ref": did}
|
| 219 |
+
if status in ("active", "on_trial") and plan in cfg.plans:
|
| 220 |
+
return {"id": event_id, "type": "subscription.plan_changed", "ref": did, "plan": plan}
|
| 221 |
+
return None
|
| 222 |
+
if name == "subscription_cancelled":
|
| 223 |
+
return {"id": event_id, "type": "subscription.canceled", "ref": did}
|
| 224 |
+
if name == "subscription_expired":
|
| 225 |
+
return {"id": event_id, "type": "subscription.expired", "ref": did}
|
| 226 |
+
return None
|