Rthur2003 commited on
Commit
7eebf49
·
1 Parent(s): f617a51

feat: add FL-MCP licensing, authentication, and credit management backend routes and services

Browse files
app/routes/flmcp.py CHANGED
@@ -1,7 +1,9 @@
1
- """FL-MCP (FL Studio AI Copilot) Commerce & Licensing Router for CrownCode.
2
 
3
- Provides end-to-end licensing, seat management, credit reservations, settlements,
4
- and payment webhooks for FL-MCP desktop clients and CrownCode web dashboard.
 
 
5
  """
6
 
7
  from __future__ import annotations
@@ -10,14 +12,15 @@ import hmac
10
  import json
11
  import os
12
  import secrets
13
- from typing import Any
14
 
15
  from fastapi import APIRouter, Header, Request, status
16
- from fastapi.responses import JSONResponse
17
  from pydantic import BaseModel, Field
18
  from starlette.concurrency import run_in_threadpool
19
 
20
- from ..services.flmcp import accounts, keys, ledger, plans, webhooks
 
 
21
  from ..services.flmcp.db import DB
22
  from ..services.flmcp.errors import ApiError
23
 
@@ -31,8 +34,7 @@ def get_db() -> DB:
31
 
32
 
33
  def get_config() -> plans.Config:
34
- cfg_path = os.environ.get("FLMCP_CONFIG")
35
- return plans.load(cfg_path)
36
 
37
 
38
  def get_topup_url() -> str:
@@ -49,10 +51,16 @@ def get_webhook_secrets() -> dict[str, str]:
49
  return {k.strip(): v.strip() for k, v in pairs}
50
 
51
 
 
 
 
 
 
 
52
  class ActivateIn(BaseModel):
53
  key: str | None = Field(default=None, max_length=64)
54
  license_key: str | None = Field(default=None, max_length=64)
55
- device_id: str | None = Field(default=None, max_length=64)
56
  name: str | None = Field(default=None, max_length=80)
57
  device_name: str | None = Field(default=None, max_length=80)
58
  replace: str | None = Field(default=None, max_length=64)
@@ -67,19 +75,8 @@ class SettleIn(BaseModel):
67
  done: list[str] = Field(default_factory=list, max_length=8)
68
 
69
 
70
- class TrialIn(BaseModel):
71
- email: str = Field(max_length=254)
72
- device_name: str | None = Field(default="Studio-PC", max_length=80)
73
-
74
-
75
- class LookupIn(BaseModel):
76
- email: str | None = Field(default=None, max_length=254)
77
- key: str | None = Field(default=None, max_length=64)
78
-
79
-
80
  class RevokeDeviceIn(BaseModel):
81
- key: str = Field(max_length=64)
82
- device_id: str = Field(max_length=64)
83
 
84
 
85
  class AdminLicenseIn(BaseModel):
@@ -101,15 +98,19 @@ def _bearer(authorization: str | None) -> str:
101
  return token.strip()
102
 
103
 
 
 
 
 
 
 
104
  def _problem_response(exc: ApiError) -> JSONResponse:
105
- headers = {"WWW-Authenticate": "Bearer"} if exc.status == 401 else {}
106
- body = {
107
- "type": "about:blank",
108
- "status": exc.status,
109
- "code": exc.code,
110
- "detail": exc.detail,
111
- **exc.extra,
112
- }
113
  if exc.code == "insufficient_credits" and "topup_url" not in body:
114
  body["topup_url"] = get_topup_url()
115
  return JSONResponse(status_code=exc.status, content=body, headers=headers, media_type="application/problem+json")
@@ -123,22 +124,21 @@ def _verify_admin(authorization: str | None) -> None:
123
  raise ApiError(401, "invalid_token", "wrong admin token")
124
 
125
 
126
- # ── Activation & Account ──────────────────────────────────────────────
127
 
128
  @router.post("/api/v1/flmcp/activate")
129
  @router.post("/v1/activate")
130
- def activate_device(body: ActivateIn):
131
- """Activate an FL-MCP desktop client with a license key."""
132
  key = body.key or body.license_key
133
  if not key:
134
  return _problem_response(ApiError(400, "bad_request", "license key is required"))
135
-
136
  dev_name = (body.name or body.device_name or "Studio-PC").strip()
137
  dev_id = (body.device_id or secrets.token_hex(8)).strip()
138
-
139
- db = get_db()
140
- cfg = get_config()
141
  try:
 
 
142
  with db.tx() as conn:
143
  return accounts.activate(conn, key, dev_id, dev_name, body.replace, db.now(), cfg)
144
  except ApiError as exc:
@@ -148,36 +148,34 @@ def activate_device(body: ActivateIn):
148
  @router.get("/api/v1/flmcp/account")
149
  @router.get("/v1/account")
150
  def get_account_status(authorization: str | None = Header(None)):
151
- """Retrieve live license balance, device seats, and costs."""
152
- db = get_db()
153
- cfg = get_config()
154
  try:
 
 
155
  with db.tx() as conn:
156
  now = db.now()
157
- lic = accounts.authenticate(conn, _bearer(authorization), now)
158
- desc = accounts.describe(conn, lic, now, cfg)
159
- dev_list = accounts.devices(conn, lic["id"])
160
  return {
161
- **desc,
162
- "devices": dev_list,
163
  "topup_url": get_topup_url(),
164
  }
165
  except ApiError as exc:
166
  return _problem_response(exc)
167
 
168
 
169
- # ── Credit Ledger (Reserve & Settle) ──────────────────────────────────
170
-
171
  @router.post("/api/v1/flmcp/credits/reserve")
172
  @router.post("/v1/credits/reserve")
173
  def reserve_credits(body: ReserveIn, authorization: str | None = Header(None)):
174
- """Reserve credits for requested FL Studio operations."""
175
- db = get_db()
176
- cfg = get_config()
177
  try:
 
 
178
  with db.tx() as conn:
179
  now = db.now()
180
- lic = accounts.authenticate(conn, _bearer(authorization), now)
181
  return ledger.reserve(conn, lic["account_id"], body.ops, body.idem, now, cfg)
182
  except ApiError as exc:
183
  return _problem_response(exc)
@@ -186,13 +184,14 @@ def reserve_credits(body: ReserveIn, authorization: str | None = Header(None)):
186
  @router.post("/api/v1/flmcp/credits/{rid}/settle")
187
  @router.post("/v1/credits/{rid}/settle")
188
  def settle_reservation(rid: str, body: SettleIn, authorization: str | None = Header(None)):
189
- """Settle charges for operations delivered successfully; refund remaining held credits."""
190
- db = get_db()
191
- cfg = get_config()
192
  try:
 
 
193
  with db.tx() as conn:
194
  now = db.now()
195
- lic = accounts.authenticate(conn, _bearer(authorization), now)
196
  return ledger.settle(conn, lic["account_id"], rid, body.done, now, cfg)
197
  except ApiError as exc:
198
  return _problem_response(exc)
@@ -201,54 +200,57 @@ def settle_reservation(rid: str, body: SettleIn, authorization: str | None = Hea
201
  @router.post("/api/v1/flmcp/devices/self/revoke", status_code=status.HTTP_204_NO_CONTENT)
202
  @router.post("/v1/devices/self/revoke", status_code=status.HTTP_204_NO_CONTENT)
203
  def revoke_calling_device(authorization: str | None = Header(None)):
204
- """Revoke license activation on the calling client machine."""
205
  db = get_db()
206
  try:
207
  with db.tx() as conn:
208
  lic = accounts.authenticate(conn, _bearer(authorization), db.now())
209
  accounts.revoke_self(conn, lic)
210
- return None
211
  except ApiError as exc:
212
  return _problem_response(exc)
213
 
214
 
215
- # ── Webhooks (Stripe / Lemon Squeezy / Paddle) ─────────────────────────
216
 
217
  @router.post("/api/v1/flmcp/webhooks/{provider}")
218
  @router.post("/v1/webhooks/{provider}")
219
  async def handle_provider_webhook(provider: str, request: Request):
220
- """Handle incoming checkout and subscription webhook events from payment providers."""
221
- db = get_db()
222
- cfg = get_config()
223
- secrets_map = get_webhook_secrets()
224
- secret = secrets_map.get(provider)
 
 
225
  if not secret:
226
- return _problem_response(ApiError(404, "unknown_provider", f"no webhook secret configured for {provider}"))
227
-
 
228
  raw_body = await request.body()
229
  if len(raw_body) > MAX_WEBHOOK:
230
  return _problem_response(ApiError(413, "too_large", "payload exceeds max size"))
231
-
232
  sig_header = (
233
  request.headers.get("x-flmcp-signature")
234
  or request.headers.get("x-signature")
235
  or request.headers.get("stripe-signature")
236
- or request.headers.get("x-hub-signature-256")
237
  )
238
-
239
- now = db.now()
240
- if not webhooks.verify(secret, sig_header, raw_body, now):
241
  return _problem_response(ApiError(401, "bad_signature", "invalid or expired webhook signature"))
242
-
243
  try:
244
  event = json.loads(raw_body)
245
  except ValueError:
246
  return _problem_response(ApiError(400, "bad_request", "payload must be valid JSON"))
247
-
248
  if not isinstance(event, dict):
249
  return _problem_response(ApiError(400, "bad_request", "payload must be a JSON object"))
250
 
251
  def _execute():
 
 
 
 
 
 
252
  with db.tx() as conn:
253
  return webhooks.apply(conn, provider, event, db.now(), cfg)
254
 
@@ -258,122 +260,114 @@ async def handle_provider_webhook(provider: str, request: Request):
258
  return _problem_response(exc)
259
 
260
 
261
- # ── User Web Dashboard Endpoints ──────────────────────────────────────
262
 
263
- @router.post("/api/v1/flmcp/user/generate-trial")
264
- def generate_trial_license(body: TrialIn):
265
- """Issue a 30-day trial license with 15 credits for CrownCode users."""
266
- db = get_db()
267
- cfg = get_config()
268
  now = db.now()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  try:
 
 
270
  with db.tx() as conn:
271
- aid = accounts.account_for(conn, body.email, now)
272
- # Check if user already has an active license
273
- existing = conn.execute(
274
- "SELECT * FROM licenses WHERE account_id=? AND status='active'",
275
- (aid,),
276
- ).fetchone()
277
- if existing:
278
- return {
279
- "account_id": aid,
280
- "existing": True,
281
- "plan": existing["plan"],
282
- "balance": ledger.balance(conn, aid, now),
283
- "devices": accounts.devices(conn, existing["id"]),
284
- "message": "Account already has an active license. Use your existing key.",
285
- }
286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  lid, key = accounts.create_license(conn, aid, "trial", now, cfg)
288
  row = conn.execute("SELECT * FROM licenses WHERE id=?", (lid,)).fetchone()
289
  accounts.start_period(conn, row, now, row["period_end"], now, cfg)
290
- return {
291
- "account_id": aid,
292
- "license_id": lid,
293
- "key": key,
294
- "plan": "trial",
295
- "balance": ledger.balance(conn, aid, now),
296
- "period_end": row["period_end"],
297
- "devices": [],
298
- }
299
  except ApiError as exc:
300
  return _problem_response(exc)
301
 
302
 
303
- @router.post("/api/v1/flmcp/user/lookup")
304
- def lookup_user_license(body: LookupIn):
305
- """Lookup license key details and device seats for the user dashboard."""
306
- db = get_db()
307
- cfg = get_config()
308
- now = db.now()
309
  try:
 
 
310
  with db.tx() as conn:
311
- lic = None
312
- if body.key:
313
- digest = keys.hash_key(body.key)
314
- if not digest:
315
- return _problem_response(ApiError(400, "bad_key", "invalid license key format"))
316
- lic = conn.execute("SELECT * FROM licenses WHERE key_hash=?", (digest,)).fetchone()
317
- elif body.email:
318
- row = conn.execute("SELECT id FROM accounts WHERE email=?", (body.email.strip().lower(),)).fetchone()
319
- if row:
320
- lic = conn.execute(
321
- "SELECT * FROM licenses WHERE account_id=? ORDER BY created_at DESC LIMIT 1",
322
- (row["id"],),
323
- ).fetchone()
324
-
325
- if not lic:
326
- return _problem_response(ApiError(404, "not_found", "no matching license found"))
327
-
328
- desc = accounts.describe(conn, lic, now, cfg)
329
- dev_list = accounts.devices(conn, lic["id"])
330
- entries = ledger.history(conn, lic["account_id"], limit=10)
331
- return {
332
- "license_id": lic["id"],
333
- "plan": lic["plan"],
334
- "status": lic["status"],
335
- "period_end": lic["period_end"],
336
- "seats_allowed": lic["seats_allowed"],
337
- "balance": desc["balance"],
338
- "costs": desc["costs"],
339
- "devices": dev_list,
340
- "recent_history": entries,
341
- }
342
  except ApiError as exc:
343
  return _problem_response(exc)
344
 
345
 
346
- @router.post("/api/v1/flmcp/devices/revoke")
347
- def revoke_device_by_id(body: RevokeDeviceIn):
348
- """Revoke a specific device seat from the web dashboard."""
349
- db = get_db()
350
  try:
 
 
351
  with db.tx() as conn:
352
- digest = keys.hash_key(body.key)
353
- if not digest:
354
- return _problem_response(ApiError(400, "bad_key", "invalid license key"))
355
- lic = conn.execute("SELECT id FROM licenses WHERE key_hash=?", (digest,)).fetchone()
356
- if not lic:
357
- return _problem_response(ApiError(404, "not_found", "license not found"))
358
- revoked = accounts.revoke_device(conn, lic["id"], body.device_id)
359
- if not revoked:
360
- return _problem_response(ApiError(404, "device_not_found", "device seat not found or already revoked"))
361
- return {"revoked": True, "device_id": body.device_id}
362
  except ApiError as exc:
363
  return _problem_response(exc)
364
 
365
 
366
- # ── Admin Endpoints ───────────────────────────────────────────────────
367
 
368
  @router.post("/api/v1/flmcp/admin/licenses")
369
  @router.post("/v1/admin/licenses")
370
  def admin_create_license(body: AdminLicenseIn, authorization: str | None = Header(None)):
371
- """Admin endpoint: Issue a new license for an email."""
372
- _verify_admin(authorization)
373
- db = get_db()
374
- cfg = get_config()
375
- now = db.now()
376
  try:
 
 
377
  with db.tx() as conn:
378
  aid = accounts.account_for(conn, body.email, now)
379
  end = now + body.days * 86400 if body.days else None
@@ -388,12 +382,10 @@ def admin_create_license(body: AdminLicenseIn, authorization: str | None = Heade
388
  @router.post("/api/v1/flmcp/admin/grants")
389
  @router.post("/v1/admin/grants")
390
  def admin_grant_credits(body: AdminGrantIn, authorization: str | None = Header(None)):
391
- """Admin endpoint: Grant manual credits to an account."""
392
- _verify_admin(authorization)
393
  db = get_db()
394
- cfg = get_config()
395
- now = db.now()
396
  try:
 
 
397
  with db.tx() as conn:
398
  aid = accounts.account_for(conn, body.email, now)
399
  end = now + body.days * 86400 if body.days else None
@@ -406,16 +398,12 @@ def admin_grant_credits(body: AdminGrantIn, authorization: str | None = Header(N
406
  @router.get("/api/v1/flmcp/admin/accounts")
407
  @router.get("/v1/admin/accounts")
408
  def admin_lookup_account(email: str, authorization: str | None = Header(None)):
409
- """Admin endpoint: Lookup an account and inspect its licenses and ledger."""
410
- _verify_admin(authorization)
411
- db = get_db()
412
- cfg = get_config()
413
- now = db.now()
414
  try:
 
 
415
  with db.tx() as conn:
416
- row = conn.execute(
417
- "SELECT id FROM accounts WHERE email=?", (email.strip().lower(),)
418
- ).fetchone()
419
  if row is None:
420
  raise ApiError(404, "not_found", "no such account")
421
  ledger.sweep(conn, row["id"], now, cfg)
@@ -430,4 +418,3 @@ def admin_lookup_account(email: str, authorization: str | None = Header(None)):
430
  }
431
  except ApiError as exc:
432
  return _problem_response(exc)
433
-
 
1
+ """FL-MCP (FL Studio AI Copilot) licensing and credit API.
2
 
3
+ Two kinds of callers:
4
+ - the desktop client, which authenticates with a device token (Bearer) after `activate`;
5
+ - the CrownCode dashboard, where the user signs in with Google through Supabase and the
6
+ Supabase access token (Bearer) is verified here. Everything under `/me` needs that session.
7
  """
8
 
9
  from __future__ import annotations
 
12
  import json
13
  import os
14
  import secrets
 
15
 
16
  from fastapi import APIRouter, Header, Request, status
17
+ from fastapi.responses import JSONResponse, Response
18
  from pydantic import BaseModel, Field
19
  from starlette.concurrency import run_in_threadpool
20
 
21
+ from ..services.client_ip import client_ip
22
+ from ..services.flmcp import accounts, keys, ledger, plans, ratelimit, webhooks
23
+ from ..services.flmcp.auth import AuthUser, bearer_user
24
  from ..services.flmcp.db import DB
25
  from ..services.flmcp.errors import ApiError
26
 
 
34
 
35
 
36
  def get_config() -> plans.Config:
37
+ return plans.load(os.environ.get("FLMCP_CONFIG"))
 
38
 
39
 
40
  def get_topup_url() -> str:
 
51
  return {k.strip(): v.strip() for k, v in pairs}
52
 
53
 
54
+ def get_ls_variants() -> dict[str, str]:
55
+ raw = os.environ.get("FLMCP_LS_VARIANTS", "")
56
+ pairs = (p.split("=", 1) for p in raw.split(",") if "=" in p)
57
+ return {k.strip(): v.strip() for k, v in pairs}
58
+
59
+
60
  class ActivateIn(BaseModel):
61
  key: str | None = Field(default=None, max_length=64)
62
  license_key: str | None = Field(default=None, max_length=64)
63
+ device_id: str | None = Field(default=None, min_length=8, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
64
  name: str | None = Field(default=None, max_length=80)
65
  device_name: str | None = Field(default=None, max_length=80)
66
  replace: str | None = Field(default=None, max_length=64)
 
75
  done: list[str] = Field(default_factory=list, max_length=8)
76
 
77
 
 
 
 
 
 
 
 
 
 
 
78
  class RevokeDeviceIn(BaseModel):
79
+ device_id: str = Field(min_length=4, max_length=64)
 
80
 
81
 
82
  class AdminLicenseIn(BaseModel):
 
98
  return token.strip()
99
 
100
 
101
+ def _token_id(token: str) -> str:
102
+ import hashlib
103
+
104
+ return hashlib.sha256(token.encode()).hexdigest()[:16]
105
+
106
+
107
  def _problem_response(exc: ApiError) -> JSONResponse:
108
+ headers: dict[str, str] = {}
109
+ if exc.status == 401:
110
+ headers["WWW-Authenticate"] = "Bearer"
111
+ if exc.status == 429 and "retry_after" in exc.extra:
112
+ headers["Retry-After"] = str(exc.extra["retry_after"])
113
+ body = {"type": "about:blank", "status": exc.status, "code": exc.code, "detail": exc.detail, **exc.extra}
 
 
114
  if exc.code == "insufficient_credits" and "topup_url" not in body:
115
  body["topup_url"] = get_topup_url()
116
  return JSONResponse(status_code=exc.status, content=body, headers=headers, media_type="application/problem+json")
 
124
  raise ApiError(401, "invalid_token", "wrong admin token")
125
 
126
 
127
+ # ── Desktop client: activation, account, credits ──────────────────────
128
 
129
  @router.post("/api/v1/flmcp/activate")
130
  @router.post("/v1/activate")
131
+ def activate_device(body: ActivateIn, request: Request):
132
+ """Activate an FL-MCP desktop client with a licence key."""
133
  key = body.key or body.license_key
134
  if not key:
135
  return _problem_response(ApiError(400, "bad_request", "license key is required"))
 
136
  dev_name = (body.name or body.device_name or "Studio-PC").strip()
137
  dev_id = (body.device_id or secrets.token_hex(8)).strip()
138
+ db, cfg = get_db(), get_config()
 
 
139
  try:
140
+ ratelimit.hit("activate_ip", client_ip(request))
141
+ ratelimit.hit("activate_key", keys.hash_key(key) or client_ip(request))
142
  with db.tx() as conn:
143
  return accounts.activate(conn, key, dev_id, dev_name, body.replace, db.now(), cfg)
144
  except ApiError as exc:
 
148
  @router.get("/api/v1/flmcp/account")
149
  @router.get("/v1/account")
150
  def get_account_status(authorization: str | None = Header(None)):
151
+ """Live balance, plan and device seats for an activated device."""
152
+ db, cfg = get_db(), get_config()
 
153
  try:
154
+ token = _bearer(authorization)
155
+ ratelimit.hit("account_token", _token_id(token))
156
  with db.tx() as conn:
157
  now = db.now()
158
+ lic = accounts.authenticate(conn, token, now)
 
 
159
  return {
160
+ **accounts.describe(conn, lic, now, cfg),
161
+ "devices": accounts.devices(conn, lic["id"]),
162
  "topup_url": get_topup_url(),
163
  }
164
  except ApiError as exc:
165
  return _problem_response(exc)
166
 
167
 
 
 
168
  @router.post("/api/v1/flmcp/credits/reserve")
169
  @router.post("/v1/credits/reserve")
170
  def reserve_credits(body: ReserveIn, authorization: str | None = Header(None)):
171
+ """Hold credits for FL Studio operations before they run."""
172
+ db, cfg = get_db(), get_config()
 
173
  try:
174
+ token = _bearer(authorization)
175
+ ratelimit.hit("reserve_token", _token_id(token))
176
  with db.tx() as conn:
177
  now = db.now()
178
+ lic = accounts.authenticate(conn, token, now)
179
  return ledger.reserve(conn, lic["account_id"], body.ops, body.idem, now, cfg)
180
  except ApiError as exc:
181
  return _problem_response(exc)
 
184
  @router.post("/api/v1/flmcp/credits/{rid}/settle")
185
  @router.post("/v1/credits/{rid}/settle")
186
  def settle_reservation(rid: str, body: SettleIn, authorization: str | None = Header(None)):
187
+ """Charge only what was delivered; the rest of the hold goes back to the balance."""
188
+ db, cfg = get_db(), get_config()
 
189
  try:
190
+ token = _bearer(authorization)
191
+ ratelimit.hit("reserve_token", _token_id(token))
192
  with db.tx() as conn:
193
  now = db.now()
194
+ lic = accounts.authenticate(conn, token, now)
195
  return ledger.settle(conn, lic["account_id"], rid, body.done, now, cfg)
196
  except ApiError as exc:
197
  return _problem_response(exc)
 
200
  @router.post("/api/v1/flmcp/devices/self/revoke", status_code=status.HTTP_204_NO_CONTENT)
201
  @router.post("/v1/devices/self/revoke", status_code=status.HTTP_204_NO_CONTENT)
202
  def revoke_calling_device(authorization: str | None = Header(None)):
203
+ """Free the seat of the machine that calls."""
204
  db = get_db()
205
  try:
206
  with db.tx() as conn:
207
  lic = accounts.authenticate(conn, _bearer(authorization), db.now())
208
  accounts.revoke_self(conn, lic)
209
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
210
  except ApiError as exc:
211
  return _problem_response(exc)
212
 
213
 
214
+ # ── Payment webhooks ──────────────────────────────────────────────────
215
 
216
  @router.post("/api/v1/flmcp/webhooks/{provider}")
217
  @router.post("/v1/webhooks/{provider}")
218
  async def handle_provider_webhook(provider: str, request: Request):
219
+ """Checkout and subscription events (signed with HMAC-SHA256)."""
220
+ db, cfg = get_db(), get_config()
221
+ try:
222
+ ratelimit.hit("webhook_ip", client_ip(request))
223
+ except ApiError as exc:
224
+ return _problem_response(exc)
225
+ secret = get_webhook_secrets().get(provider)
226
  if not secret:
227
+ return _problem_response(ApiError(404, "unknown_provider", "no such provider"))
228
+ if int(request.headers.get("content-length") or 0) > MAX_WEBHOOK:
229
+ return _problem_response(ApiError(413, "too_large", "payload exceeds max size"))
230
  raw_body = await request.body()
231
  if len(raw_body) > MAX_WEBHOOK:
232
  return _problem_response(ApiError(413, "too_large", "payload exceeds max size"))
 
233
  sig_header = (
234
  request.headers.get("x-flmcp-signature")
235
  or request.headers.get("x-signature")
236
  or request.headers.get("stripe-signature")
 
237
  )
238
+ if not webhooks.verify(secret, sig_header, raw_body, db.now()):
 
 
239
  return _problem_response(ApiError(401, "bad_signature", "invalid or expired webhook signature"))
 
240
  try:
241
  event = json.loads(raw_body)
242
  except ValueError:
243
  return _problem_response(ApiError(400, "bad_request", "payload must be valid JSON"))
 
244
  if not isinstance(event, dict):
245
  return _problem_response(ApiError(400, "bad_request", "payload must be a JSON object"))
246
 
247
  def _execute():
248
+ nonlocal event
249
+ if provider == "lemonsqueezy":
250
+ normalized = webhooks.normalize_lemonsqueezy(event, get_ls_variants(), cfg)
251
+ if normalized is None:
252
+ return {"ignored": True}
253
+ event = normalized
254
  with db.tx() as conn:
255
  return webhooks.apply(conn, provider, event, db.now(), cfg)
256
 
 
260
  return _problem_response(exc)
261
 
262
 
263
+ # ── Dashboard (Google sign-in through Supabase) ───────────────────────
264
 
265
+ def _summary(conn, db: DB, cfg: plans.Config, aid: str) -> dict:
 
 
 
 
266
  now = db.now()
267
+ ledger.sweep(conn, aid, now, cfg)
268
+ lic = accounts.latest_license(conn, aid)
269
+ out: dict = {
270
+ "balance": ledger.balance(conn, aid, now),
271
+ "costs": cfg.costs,
272
+ "trial_used": accounts.trial_used(conn, aid),
273
+ "history": ledger.history(conn, aid, limit=10),
274
+ "license": None,
275
+ "devices": [],
276
+ "topup_url": get_topup_url(),
277
+ }
278
+ if lic is not None:
279
+ out["license"] = {
280
+ "id": lic["id"],
281
+ "plan": lic["plan"],
282
+ "status": lic["status"],
283
+ "period_end": lic["period_end"],
284
+ "seats_allowed": lic["seats_allowed"],
285
+ }
286
+ out["devices"] = accounts.devices(conn, lic["id"])
287
+ return out
288
+
289
+
290
+ @router.get("/api/v1/flmcp/me")
291
+ def me_summary(request: Request, authorization: str | None = Header(None)):
292
+ """The signed-in user's licence, credits and devices. Creates the account on first sign-in."""
293
+ db, cfg = get_db(), get_config()
294
  try:
295
+ user: AuthUser = bearer_user(authorization)
296
+ ratelimit.hit("me_user", user.id)
297
  with db.tx() as conn:
298
+ aid = accounts.account_for_user(conn, user.id, user.email, db.now())
299
+ return {"email": user.email, **_summary(conn, db, cfg, aid)}
300
+ except ApiError as exc:
301
+ return _problem_response(exc)
 
 
 
 
 
 
 
 
 
 
 
302
 
303
+
304
+ @router.post("/api/v1/flmcp/me/trial")
305
+ def me_claim_trial(request: Request, authorization: str | None = Header(None)):
306
+ """One free trial per account: 15 credits for 30 days. The key is shown once."""
307
+ db, cfg = get_db(), get_config()
308
+ try:
309
+ user = bearer_user(authorization)
310
+ ratelimit.hit("trial_ip", client_ip(request))
311
+ ratelimit.hit("trial_user", user.id)
312
+ domain = user.email.rsplit("@", 1)[-1]
313
+ if domain in accounts.DISPOSABLE_DOMAINS:
314
+ raise ApiError(403, "email_not_allowed", "use a permanent email address to claim a trial")
315
+ now = db.now()
316
+ with db.tx() as conn:
317
+ aid = accounts.account_for_user(conn, user.id, user.email, now)
318
+ if accounts.trial_used(conn, aid):
319
+ raise ApiError(409, "trial_used", "this account has already used its free trial")
320
  lid, key = accounts.create_license(conn, aid, "trial", now, cfg)
321
  row = conn.execute("SELECT * FROM licenses WHERE id=?", (lid,)).fetchone()
322
  accounts.start_period(conn, row, now, row["period_end"], now, cfg)
323
+ return {"key": key, **_summary(conn, db, cfg, aid)}
 
 
 
 
 
 
 
 
324
  except ApiError as exc:
325
  return _problem_response(exc)
326
 
327
 
328
+ @router.post("/api/v1/flmcp/me/key/rotate")
329
+ def me_rotate_key(authorization: str | None = Header(None)):
330
+ """Issue a new licence key (the old one stops activating new devices). Shown once."""
331
+ db, cfg = get_db(), get_config()
 
 
332
  try:
333
+ user = bearer_user(authorization)
334
+ ratelimit.hit("rotate_user", user.id)
335
  with db.tx() as conn:
336
+ aid = accounts.account_for_user(conn, user.id, user.email, db.now())
337
+ lic = accounts.latest_license(conn, aid)
338
+ if lic is None:
339
+ raise ApiError(404, "no_license", "this account has no licence yet")
340
+ return {"key": accounts.rotate_key(conn, lic["id"]), **_summary(conn, db, cfg, aid)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  except ApiError as exc:
342
  return _problem_response(exc)
343
 
344
 
345
+ @router.post("/api/v1/flmcp/me/devices/revoke")
346
+ def me_revoke_device(body: RevokeDeviceIn, authorization: str | None = Header(None)):
347
+ """Free one seat from the dashboard."""
348
+ db, cfg = get_db(), get_config()
349
  try:
350
+ user = bearer_user(authorization)
351
+ ratelimit.hit("me_user", user.id)
352
  with db.tx() as conn:
353
+ aid = accounts.account_for_user(conn, user.id, user.email, db.now())
354
+ lic = accounts.latest_license(conn, aid)
355
+ if lic is None or not accounts.revoke_device(conn, lic["id"], body.device_id):
356
+ raise ApiError(404, "device_not_found", "device seat not found or already revoked")
357
+ return _summary(conn, db, cfg, aid)
 
 
 
 
 
358
  except ApiError as exc:
359
  return _problem_response(exc)
360
 
361
 
362
+ # ── Admin ─────────────────────────────────────────────────────────────
363
 
364
  @router.post("/api/v1/flmcp/admin/licenses")
365
  @router.post("/v1/admin/licenses")
366
  def admin_create_license(body: AdminLicenseIn, authorization: str | None = Header(None)):
367
+ db, cfg = get_db(), get_config()
 
 
 
 
368
  try:
369
+ _verify_admin(authorization)
370
+ now = db.now()
371
  with db.tx() as conn:
372
  aid = accounts.account_for(conn, body.email, now)
373
  end = now + body.days * 86400 if body.days else None
 
382
  @router.post("/api/v1/flmcp/admin/grants")
383
  @router.post("/v1/admin/grants")
384
  def admin_grant_credits(body: AdminGrantIn, authorization: str | None = Header(None)):
 
 
385
  db = get_db()
 
 
386
  try:
387
+ _verify_admin(authorization)
388
+ now = db.now()
389
  with db.tx() as conn:
390
  aid = accounts.account_for(conn, body.email, now)
391
  end = now + body.days * 86400 if body.days else None
 
398
  @router.get("/api/v1/flmcp/admin/accounts")
399
  @router.get("/v1/admin/accounts")
400
  def admin_lookup_account(email: str, authorization: str | None = Header(None)):
401
+ db, cfg = get_db(), get_config()
 
 
 
 
402
  try:
403
+ _verify_admin(authorization)
404
+ now = db.now()
405
  with db.tx() as conn:
406
+ row = conn.execute("SELECT id FROM accounts WHERE email=?", (email.strip().lower(),)).fetchone()
 
 
407
  if row is None:
408
  raise ApiError(404, "not_found", "no such account")
409
  ledger.sweep(conn, row["id"], now, cfg)
 
418
  }
419
  except ApiError as exc:
420
  return _problem_response(exc)
 
app/services/flmcp/auth.py CHANGED
@@ -65,3 +65,4 @@ def bearer_user(authorization: str | None) -> AuthUser:
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())
 
 
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())
68
+
app/services/flmcp/ratelimit.py CHANGED
@@ -51,3 +51,4 @@ def hit(bucket: str, key: str, now: float | None = None) -> None:
51
  def reset() -> None:
52
  with _lock:
53
  _hits.clear()
 
 
51
  def reset() -> None:
52
  with _lock:
53
  _hits.clear()
54
+
requirements.txt CHANGED
@@ -76,3 +76,5 @@ youtube-transcript-api>=0.6.2
76
 
77
  # === FL-MCP Database Persistence (PostgreSQL for external DB) ===
78
  psycopg2-binary>=2.9.9
 
 
 
76
 
77
  # === FL-MCP Database Persistence (PostgreSQL for external DB) ===
78
  psycopg2-binary>=2.9.9
79
+ # Verifies Supabase (Google sign-in) access tokens against the project's JWKS
80
+ pyjwt[crypto]>=2.8.0