Rthur2003 commited on
Commit
e704e6c
·
1 Parent(s): 3067a0c

feat: add FL-MCP licensing, seat management, credit ledger, and payment webhooks backend

Browse files
app/main.py CHANGED
@@ -20,6 +20,7 @@ from .routes.commend import router as commend_router
20
  from .routes.reservations import router as reservations_router
21
  from .routes.dreams import router as dreams_router
22
  from .routes.remix import router as remix_router
 
23
  from .services.logging_config import setup_logging, get_logger
24
 
25
 
@@ -105,7 +106,15 @@ app.add_middleware(
105
  allow_origins=_origins,
106
  allow_credentials="*" not in _origins,
107
  allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
108
- allow_headers=["Content-Type", "Accept"],
 
 
 
 
 
 
 
 
109
  expose_headers=["X-Remix-Analysis", "X-Multitrack-Analysis"],
110
  )
111
 
@@ -117,5 +126,6 @@ app.include_router(commend_router)
117
  app.include_router(reservations_router)
118
  app.include_router(dreams_router)
119
  app.include_router(remix_router)
 
120
 
121
  logger.info("CrownCode backend API initialized")
 
20
  from .routes.reservations import router as reservations_router
21
  from .routes.dreams import router as dreams_router
22
  from .routes.remix import router as remix_router
23
+ from .routes.flmcp import router as flmcp_router
24
  from .services.logging_config import setup_logging, get_logger
25
 
26
 
 
106
  allow_origins=_origins,
107
  allow_credentials="*" not in _origins,
108
  allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
109
+ allow_headers=[
110
+ "Content-Type",
111
+ "Accept",
112
+ "Authorization",
113
+ "X-Signature",
114
+ "X-FLMCP-Signature",
115
+ "X-Hub-Signature-256",
116
+ "stripe-signature",
117
+ ],
118
  expose_headers=["X-Remix-Analysis", "X-Multitrack-Analysis"],
119
  )
120
 
 
126
  app.include_router(reservations_router)
127
  app.include_router(dreams_router)
128
  app.include_router(remix_router)
129
+ app.include_router(flmcp_router)
130
 
131
  logger.info("CrownCode backend API initialized")
app/routes/flmcp.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
8
+
9
+ 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
+
24
+ router = APIRouter(tags=["FL-MCP Licensing & Credits"])
25
+
26
+ MAX_WEBHOOK = 64 * 1024
27
+
28
+
29
+ def get_db() -> DB:
30
+ return 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:
39
+ return os.environ.get("FLMCP_TOPUP_URL", "https://hasan-arthur-altuntas.xyz/fl-mcp#pricing")
40
+
41
+
42
+ def get_admin_token() -> str:
43
+ return os.environ.get("FLMCP_ADMIN_TOKEN", "")
44
+
45
+
46
+ def get_webhook_secrets() -> dict[str, str]:
47
+ raw = os.environ.get("FLMCP_WEBHOOK_SECRETS", "")
48
+ pairs = (p.split("=", 1) for p in raw.split(",") if "=" in p)
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)
59
+
60
+
61
+ class ReserveIn(BaseModel):
62
+ ops: list[str] = Field(min_length=1, max_length=8)
63
+ idem: str = Field(min_length=8, max_length=64)
64
+
65
+
66
+ 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):
86
+ email: str = Field(max_length=254)
87
+ plan: str = Field(max_length=32)
88
+ days: int | None = Field(default=None, ge=1, le=3660)
89
+
90
+
91
+ class AdminGrantIn(BaseModel):
92
+ email: str = Field(max_length=254)
93
+ credits: int = Field(gt=0, le=1_000_000)
94
+ days: int | None = Field(default=None, ge=1, le=3660)
95
+
96
+
97
+ def _bearer(authorization: str | None) -> str:
98
+ scheme, _, token = (authorization or "").partition(" ")
99
+ if scheme.lower() != "bearer" or not token.strip():
100
+ raise ApiError(401, "invalid_token", "send the device token as 'Authorization: Bearer <token>'")
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")
116
+
117
+
118
+ def _verify_admin(authorization: str | None) -> None:
119
+ admin_token = get_admin_token()
120
+ if not admin_token:
121
+ raise ApiError(404, "not_found", "admin API is not enabled")
122
+ if not hmac.compare_digest(_bearer(authorization).encode(), admin_token.encode()):
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:
145
+ return _problem_response(exc)
146
+
147
+
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)
184
+
185
+
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)
199
+
200
+
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
+
255
+ try:
256
+ return await run_in_threadpool(_execute)
257
+ except ApiError as exc:
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
380
+ lid, key = accounts.create_license(conn, aid, body.plan, now, cfg, end)
381
+ row = conn.execute("SELECT * FROM licenses WHERE id=?", (lid,)).fetchone()
382
+ accounts.start_period(conn, row, now, row["period_end"], now, cfg)
383
+ return {"license": lid, "key": key, "plan": body.plan, "period_end": row["period_end"]}
384
+ except ApiError as exc:
385
+ return _problem_response(exc)
386
+
387
+
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
400
+ ledger.grant(conn, aid, "adjust", body.credits, now, end)
401
+ return {"balance": ledger.balance(conn, aid, now)}
402
+ except ApiError as exc:
403
+ return _problem_response(exc)
404
+
405
+
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)
422
+ lics = conn.execute(
423
+ "SELECT id, plan, status, period_end, seats_allowed FROM licenses WHERE account_id=?",
424
+ (row["id"],),
425
+ ).fetchall()
426
+ return {
427
+ "balance": ledger.balance(conn, row["id"], now),
428
+ "licenses": [dict(r) for r in lics],
429
+ "entries": ledger.history(conn, row["id"]),
430
+ }
431
+ except ApiError as exc:
432
+ return _problem_response(exc)
app/services/flmcp/__init__.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FL-MCP Commerce & Licensing Package for CrownCode."""
2
+
3
+ from .accounts import (
4
+ account_for,
5
+ activate,
6
+ authenticate,
7
+ create_license,
8
+ describe,
9
+ devices,
10
+ revoke_device,
11
+ revoke_self,
12
+ start_period,
13
+ )
14
+ from .db import DB, default_db_path
15
+ from .errors import ApiError
16
+ from .keys import display, hash_key, new_key, normalize
17
+ from .ledger import balance, grant, history, reserve, settle, sweep
18
+ from .plans import Config, Plan, load, require_usable, usable
19
+ from .webhooks import apply, sign, verify
20
+
21
+ __all__ = [
22
+ "DB",
23
+ "default_db_path",
24
+ "ApiError",
25
+ "Config",
26
+ "Plan",
27
+ "load",
28
+ "usable",
29
+ "require_usable",
30
+ "new_key",
31
+ "normalize",
32
+ "hash_key",
33
+ "display",
34
+ "account_for",
35
+ "create_license",
36
+ "start_period",
37
+ "activate",
38
+ "describe",
39
+ "authenticate",
40
+ "revoke_self",
41
+ "revoke_device",
42
+ "devices",
43
+ "grant",
44
+ "balance",
45
+ "sweep",
46
+ "reserve",
47
+ "settle",
48
+ "history",
49
+ "verify",
50
+ "sign",
51
+ "apply",
52
+ ]
app/services/flmcp/accounts.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Accounts, licences and device activations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import secrets
8
+ import uuid
9
+ from typing import Any
10
+
11
+ from . import keys, ledger
12
+ from .errors import ApiError
13
+ from .plans import Config, require_usable
14
+
15
+
16
+ def _hash(token: str) -> str:
17
+ return hashlib.sha256(token.encode()).hexdigest()
18
+
19
+
20
+ def _spec(cfg: Config, plan: str):
21
+ if plan not in cfg.plans:
22
+ raise ApiError(409, "unknown_plan", f"plan '{plan}' is no longer offered; contact support")
23
+ return cfg.plans[plan]
24
+
25
+
26
+ def account_for(conn: Any, email: str, now: int) -> str:
27
+ email = email.strip().lower()
28
+ if "@" not in email:
29
+ raise ApiError(400, "bad_request", "a valid email is required")
30
+ row = conn.execute("SELECT id FROM accounts WHERE email=?", (email,)).fetchone()
31
+ if row:
32
+ return row["id"]
33
+ aid = uuid.uuid4().hex
34
+ conn.execute(
35
+ "INSERT INTO accounts(id, email, created_at) VALUES (?,?,?)",
36
+ (aid, email, now),
37
+ )
38
+ return aid
39
+
40
+
41
+ def create_license(
42
+ conn: Any,
43
+ account_id: str,
44
+ plan: str,
45
+ now: int,
46
+ cfg: Config,
47
+ period_end: int | None = None,
48
+ provider: str = "",
49
+ ref: str = "",
50
+ renews: bool = False,
51
+ seats_allowed: int | None = None,
52
+ ) -> tuple[str, str]:
53
+ """Returns (licence id, the licence key). The key is stored hashed and cannot be retrieved again."""
54
+ if plan not in cfg.plans:
55
+ raise ApiError(400, "unknown_plan", f"unknown plan '{plan}'")
56
+ spec = cfg.plans[plan]
57
+ if period_end is None and spec.days:
58
+ period_end = now + spec.days * 86400
59
+ key = keys.new_key()
60
+ lid = uuid.uuid4().hex
61
+ status = "active" if renews or period_end is None else "canceled"
62
+ seats = seats_allowed if seats_allowed is not None else spec.devices
63
+ conn.execute(
64
+ "INSERT INTO licenses(id, account_id, key_hash, plan, status, period_end, seats_allowed,"
65
+ " provider, provider_ref, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
66
+ (lid, account_id, keys.hash_key(key), plan, status, period_end, seats, provider, ref, now),
67
+ )
68
+ return lid, key
69
+
70
+
71
+ def start_period(
72
+ conn: Any,
73
+ lic: Any,
74
+ period_start: int,
75
+ period_end: int | None,
76
+ now: int,
77
+ cfg: Config,
78
+ ) -> bool:
79
+ """Give a licence its allowance for one billing period."""
80
+ spec = _spec(cfg, lic["plan"])
81
+ source = f"plan:{lic['id']}:{period_start}"
82
+ return ledger.grant(conn, lic["account_id"], "plan", spec.credits, now, period_end, source)
83
+
84
+
85
+ def outbox_add(conn: Any, account_id: str, kind: str, payload: dict, now: int):
86
+ conn.execute(
87
+ "INSERT INTO outbox(account_id, kind, payload, created_at) VALUES (?,?,?,?)",
88
+ (account_id, kind, json.dumps(payload), now),
89
+ )
90
+
91
+
92
+ def activate(
93
+ conn: Any,
94
+ key: str,
95
+ device_id: str,
96
+ name: str,
97
+ replace: str | None,
98
+ now: int,
99
+ cfg: Config,
100
+ ) -> dict:
101
+ digest = keys.hash_key(key)
102
+ if digest is None:
103
+ raise ApiError(400, "bad_key", "that is not a valid licence key; check it for typos")
104
+ lic = conn.execute("SELECT * FROM licenses WHERE key_hash=?", (digest,)).fetchone()
105
+ if lic is None:
106
+ raise ApiError(404, "unknown_key", "licence key not found")
107
+ require_usable(lic["status"], lic["period_end"], now)
108
+ limit = lic.get("seats_allowed") if isinstance(lic, dict) and lic.get("seats_allowed") else _spec(cfg, lic["plan"]).devices
109
+
110
+ mine = conn.execute(
111
+ "SELECT * FROM devices WHERE license_id=? AND device_id=?", (lic["id"], device_id)
112
+ ).fetchone()
113
+ others = [
114
+ d
115
+ for d in conn.execute(
116
+ "SELECT * FROM devices WHERE license_id=? AND revoked=0 ORDER BY last_seen",
117
+ (lic["id"],),
118
+ ).fetchall()
119
+ if d["device_id"] != device_id
120
+ ]
121
+ if (mine is None or mine["revoked"]) and len(others) >= limit:
122
+ victims = [
123
+ d
124
+ for d in others
125
+ if replace
126
+ and (d["name"] == replace or (len(replace) >= 4 and d["device_id"].startswith(replace)))
127
+ ]
128
+ if len(victims) > 1:
129
+ raise ApiError(409, "ambiguous_replace", "more than one device matches; use its id")
130
+ if victims:
131
+ conn.execute("UPDATE devices SET revoked=1 WHERE pk=?", (victims[0]["pk"],))
132
+ others.remove(victims[0])
133
+ if len(others) >= limit:
134
+ raise ApiError(
135
+ 409,
136
+ "device_limit",
137
+ f"this licence allows {limit} device(s); sign one out or pass replace",
138
+ devices=[
139
+ {"id": d["device_id"][:8], "name": d["name"], "last_seen": d["last_seen"]}
140
+ for d in others
141
+ ],
142
+ )
143
+ token = secrets.token_urlsafe(32)
144
+ if mine is None:
145
+ conn.execute(
146
+ "INSERT INTO devices(license_id, device_id, name, token_hash, created_at, last_seen)"
147
+ " VALUES (?,?,?,?,?,?)",
148
+ (lic["id"], device_id, name, _hash(token), now, now),
149
+ )
150
+ else:
151
+ conn.execute(
152
+ "UPDATE devices SET name=?, token_hash=?, last_seen=?, revoked=0 WHERE pk=?",
153
+ (name, _hash(token), now, mine["pk"]),
154
+ )
155
+ desc = describe(conn, lic, now, cfg)
156
+ return {
157
+ "token": token,
158
+ "device_token": token,
159
+ **desc,
160
+ }
161
+
162
+
163
+ def describe(conn: Any, lic: Any, now: int, cfg: Config) -> dict:
164
+ ledger.sweep(conn, lic["account_id"], now, cfg)
165
+ return {
166
+ "plan": lic["plan"],
167
+ "status": lic["status"],
168
+ "period_end": lic["period_end"],
169
+ "balance": ledger.balance(conn, lic["account_id"], now),
170
+ "costs": cfg.costs,
171
+ }
172
+
173
+
174
+ def authenticate(conn: Any, token: str, now: int) -> Any:
175
+ """The licence a device token belongs to."""
176
+ row = conn.execute(
177
+ "SELECT l.*, d.pk AS device_pk, d.device_id FROM devices d"
178
+ " JOIN licenses l ON l.id = d.license_id WHERE d.token_hash=? AND d.revoked=0",
179
+ (_hash(token),),
180
+ ).fetchone()
181
+ if row is None:
182
+ raise ApiError(401, "invalid_token", "this device is not activated; sign in again")
183
+ require_usable(row["status"], row["period_end"], now)
184
+ conn.execute("UPDATE devices SET last_seen=? WHERE pk=?", (now, row["device_pk"]))
185
+ return row
186
+
187
+
188
+ def revoke_self(conn: Any, lic: Any) -> None:
189
+ conn.execute("UPDATE devices SET revoked=1 WHERE pk=?", (lic["device_pk"],))
190
+
191
+
192
+ def revoke_device(conn: Any, license_id: str, device_id_prefix: str) -> bool:
193
+ """Revoke a device by device_id or prefix from the dashboard."""
194
+ rows = conn.execute(
195
+ "SELECT pk, device_id FROM devices WHERE license_id=? AND revoked=0",
196
+ (license_id,),
197
+ ).fetchall()
198
+ matches = [r for r in rows if r["device_id"] == device_id_prefix or r["device_id"].startswith(device_id_prefix)]
199
+ if not matches:
200
+ return False
201
+ for m in matches:
202
+ conn.execute("UPDATE devices SET revoked=1 WHERE pk=?", (m["pk"],))
203
+ return True
204
+
205
+
206
+ def devices(conn: Any, license_id: str) -> list[dict]:
207
+ rows = conn.execute(
208
+ "SELECT device_id, name, created_at, last_seen FROM devices WHERE license_id=? AND revoked=0"
209
+ " ORDER BY last_seen DESC",
210
+ (license_id,),
211
+ ).fetchall()
212
+ return [
213
+ {
214
+ "id": r["device_id"][:8],
215
+ "full_id": r["device_id"],
216
+ "name": r["name"],
217
+ "created_at": r["created_at"],
218
+ "last_seen": r["last_seen"],
219
+ }
220
+ for r in rows
221
+ ]
app/services/flmcp/ledger.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Credit ledger.
2
+
3
+ Credits live in lots (monthly allowance, top-up pack, grant, refund).
4
+ A lot that expires earlier is used first.
5
+ reserve() debits the lots immediately and tracks origin lots.
6
+ settle() charges the price of completed work and returns the remainder to the same lots.
7
+ A reservation that is not settled expires and is returned in full when hold_seconds passes.
8
+ Every movement is logged in `entries`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import uuid
15
+ from typing import Any
16
+
17
+ from .errors import ApiError
18
+ from .plans import Config
19
+
20
+
21
+ def _new_lot(
22
+ conn: Any,
23
+ account_id: str,
24
+ kind: str,
25
+ amount: int,
26
+ now: int,
27
+ expires_at: int | None,
28
+ source: str | None,
29
+ ) -> int | None:
30
+ cur = conn.execute(
31
+ "INSERT OR IGNORE INTO lots(account_id, kind, amount, remaining, expires_at, source,"
32
+ " created_at) VALUES (?,?,?,?,?,?,?)",
33
+ (account_id, kind, amount, amount, expires_at, source, now),
34
+ )
35
+ return cur.lastrowid if cur.rowcount else None
36
+
37
+
38
+ def _entry(conn: Any, account_id: str, now: int, kind: str, amount: int, ref: str):
39
+ conn.execute(
40
+ "INSERT INTO entries(account_id, ts, kind, amount, ref) VALUES (?,?,?,?,?)",
41
+ (account_id, now, kind, amount, ref),
42
+ )
43
+
44
+
45
+ def grant(
46
+ conn: Any,
47
+ account_id: str,
48
+ kind: str,
49
+ amount: int,
50
+ now: int,
51
+ expires_at: int | None = None,
52
+ source: str | None = None,
53
+ ) -> bool:
54
+ """Add credits. A source (e.g. 'plan:<licence>:<period>') makes the grant happen only once."""
55
+ if amount <= 0 or (expires_at is not None and expires_at <= now):
56
+ return False
57
+ lot = _new_lot(conn, account_id, kind, amount, now, expires_at, source)
58
+ if lot is None:
59
+ return False
60
+ _entry(conn, account_id, now, "grant", amount, f"lot:{lot}")
61
+ return True
62
+
63
+
64
+ def balance(conn: Any, account_id: str, now: int) -> int:
65
+ row = conn.execute(
66
+ "SELECT COALESCE(SUM(remaining), 0) AS total FROM lots"
67
+ " WHERE account_id=? AND (expires_at IS NULL OR expires_at>?)",
68
+ (account_id, now),
69
+ ).fetchone()
70
+ if row is None:
71
+ return 0
72
+ return int(row["total"] if isinstance(row, dict) else row[0])
73
+
74
+
75
+ def _give_back(conn: Any, res: Any, amount: int, now: int, cfg: Config):
76
+ """Return `amount` of a reservation to the lots it came from, the last one taken first."""
77
+ left = amount
78
+ alloc_list = json.loads(res["alloc"]) if isinstance(res["alloc"], str) else res["alloc"]
79
+ for lot_id, taken in reversed(alloc_list):
80
+ if left <= 0:
81
+ break
82
+ part = min(taken, left)
83
+ lot = conn.execute("SELECT expires_at FROM lots WHERE id=?", (lot_id,)).fetchone()
84
+ if lot and (lot["expires_at"] is None or lot["expires_at"] > now):
85
+ conn.execute("UPDATE lots SET remaining = remaining + ? WHERE id=?", (part, lot_id))
86
+ else:
87
+ # Lot expired in the meantime: customer gets credits back with refund shelf life
88
+ expires = now + cfg.refund_days * 86400
89
+ _new_lot(conn, res["account_id"], "refund", part, now, expires, None)
90
+ left -= part
91
+ _entry(conn, res["account_id"], now, "release", amount, f"res:{res['id']}")
92
+
93
+
94
+ def sweep(conn: Any, account_id: str, now: int, cfg: Config) -> None:
95
+ """Return holds that timed out and drop lots that expired."""
96
+ stale = conn.execute(
97
+ "SELECT * FROM reservations WHERE account_id=? AND state='held' AND expires_at<=?",
98
+ (account_id, now),
99
+ ).fetchall()
100
+ for res in stale:
101
+ _give_back(conn, res, res["cost"], now, cfg)
102
+ conn.execute(
103
+ "UPDATE reservations SET state='expired', settled_at=? WHERE id=?", (now, res["id"])
104
+ )
105
+ old = conn.execute(
106
+ "SELECT id, remaining FROM lots WHERE account_id=? AND remaining>0"
107
+ " AND expires_at IS NOT NULL AND expires_at<=?",
108
+ (account_id, now),
109
+ ).fetchall()
110
+ for lot in old:
111
+ conn.execute("UPDATE lots SET remaining=0 WHERE id=?", (lot["id"],))
112
+ _entry(conn, account_id, now, "expire", -lot["remaining"], f"lot:{lot['id']}")
113
+
114
+
115
+ def _view(conn: Any, res: Any, now: int) -> dict:
116
+ out = {
117
+ "id": res["id"],
118
+ "state": res["state"],
119
+ "cost": res["cost"],
120
+ "balance": balance(conn, res["account_id"], now),
121
+ }
122
+ if res["state"] == "held":
123
+ out["expires_at"] = res["expires_at"]
124
+ if res["state"] == "settled":
125
+ out["charged"] = res["charged"]
126
+ out["refunded"] = res["cost"] - (res["charged"] or 0)
127
+ return out
128
+
129
+
130
+ def reserve(
131
+ conn: Any,
132
+ account_id: str,
133
+ ops: list[str],
134
+ idem: str,
135
+ now: int,
136
+ cfg: Config,
137
+ ) -> dict:
138
+ prices = {}
139
+ for op in ops:
140
+ if op not in cfg.costs:
141
+ raise ApiError(400, "unknown_op", f"unknown operation '{op}'")
142
+ prices[op] = cfg.costs[op]
143
+ if not prices or len(prices) != len(ops):
144
+ raise ApiError(400, "bad_request", "ops must be a non-empty list of distinct names")
145
+ sweep(conn, account_id, now, cfg)
146
+ again = conn.execute(
147
+ "SELECT * FROM reservations WHERE account_id=? AND idem=?", (account_id, idem)
148
+ ).fetchone()
149
+ if again is not None:
150
+ ops_recorded = json.loads(again["ops"]) if isinstance(again["ops"], str) else again["ops"]
151
+ if set(ops_recorded) != set(ops):
152
+ raise ApiError(409, "idempotency_conflict", "that key was used for other operations")
153
+ return _view(conn, again, now)
154
+ cost = sum(prices.values())
155
+ have = balance(conn, account_id, now)
156
+ if have < cost:
157
+ raise ApiError(
158
+ 402,
159
+ "insufficient_credits",
160
+ f"needs {cost} credits, balance is {have}",
161
+ cost=cost,
162
+ balance=have,
163
+ )
164
+ alloc, left = [], cost
165
+ lots = conn.execute(
166
+ "SELECT id, remaining FROM lots WHERE account_id=? AND remaining>0"
167
+ " AND (expires_at IS NULL OR expires_at>?) ORDER BY expires_at IS NULL, expires_at, id",
168
+ (account_id, now),
169
+ ).fetchall()
170
+ for lot in lots:
171
+ part = min(lot["remaining"], left)
172
+ conn.execute("UPDATE lots SET remaining = remaining - ? WHERE id=?", (part, lot["id"]))
173
+ alloc.append([lot["id"], part])
174
+ left -= part
175
+ if not left:
176
+ break
177
+ rid = uuid.uuid4().hex
178
+ conn.execute(
179
+ "INSERT INTO reservations(id, account_id, idem, state, ops, cost, alloc, created_at,"
180
+ " expires_at) VALUES (?,?,?,?,?,?,?,?,?)",
181
+ (
182
+ rid,
183
+ account_id,
184
+ idem,
185
+ "held",
186
+ json.dumps(prices),
187
+ cost,
188
+ json.dumps(alloc),
189
+ now,
190
+ now + cfg.hold_seconds,
191
+ ),
192
+ )
193
+ _entry(conn, account_id, now, "hold", -cost, f"res:{rid}")
194
+ return {
195
+ "id": rid,
196
+ "state": "held",
197
+ "cost": cost,
198
+ "balance": have - cost,
199
+ "expires_at": now + cfg.hold_seconds,
200
+ }
201
+
202
+
203
+ def settle(
204
+ conn: Any, account_id: str, rid: str, done: list[str], now: int, cfg: Config
205
+ ) -> dict:
206
+ """Charge for the operations in `done` (those that were delivered) and return the rest."""
207
+ sweep(conn, account_id, now, cfg)
208
+ res = conn.execute(
209
+ "SELECT * FROM reservations WHERE id=? AND account_id=?", (rid, account_id)
210
+ ).fetchone()
211
+ if res is None:
212
+ raise ApiError(404, "unknown_reservation", "no such reservation")
213
+ prices = json.loads(res["ops"]) if isinstance(res["ops"], str) else res["ops"]
214
+ if len(set(done)) != len(done) or not set(done) <= set(prices):
215
+ raise ApiError(400, "bad_request", "done must be distinct operations that were reserved")
216
+ if res["state"] == "expired":
217
+ raise ApiError(409, "reservation_expired", "the hold timed out; the credits came back")
218
+ if res["state"] == "settled":
219
+ done_recorded = json.loads(res["done"]) if isinstance(res["done"], str) else res["done"]
220
+ if sorted(done_recorded) != sorted(done):
221
+ raise ApiError(409, "already_settled", "this reservation was settled differently")
222
+ return _view(conn, res, now)
223
+ charge = sum(prices[op] for op in done)
224
+ if res["cost"] - charge:
225
+ _give_back(conn, res, res["cost"] - charge, now, cfg)
226
+ conn.execute(
227
+ "UPDATE reservations SET state='settled', done=?, charged=?, settled_at=? WHERE id=?",
228
+ (json.dumps(done), charge, now, rid),
229
+ )
230
+ res = conn.execute("SELECT * FROM reservations WHERE id=?", (rid,)).fetchone()
231
+ return _view(conn, res, now)
232
+
233
+
234
+ def history(conn: Any, account_id: str, limit: int = 20) -> list[dict]:
235
+ rows = conn.execute(
236
+ "SELECT ts, kind, amount, ref FROM entries WHERE account_id=? ORDER BY id DESC LIMIT ?",
237
+ (account_id, limit),
238
+ ).fetchall()
239
+ return [dict(r) for r in rows]
app/services/flmcp/webhooks.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Webhook adapter for Stripe, Lemon Squeezy, and Paddle."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import hmac
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ from . import accounts, ledger
11
+ from .errors import ApiError
12
+ from .plans import Config
13
+
14
+ TOLERANCE = 300
15
+
16
+
17
+ def sign(secret: str, body: bytes, t: int) -> str:
18
+ mac = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
19
+ return f"t={t},v1={mac}"
20
+
21
+
22
+ def verify(secret: str, header: str | None, body: bytes, now: int) -> bool:
23
+ if not secret or not header:
24
+ return False
25
+
26
+ # Check for direct hex signature or t=...,v1=...
27
+ if "," in header and "v1=" in header:
28
+ try:
29
+ parts = dict(p.split("=", 1) for p in header.split(","))
30
+ t = int(parts["t"])
31
+ got = parts["v1"]
32
+ except (KeyError, ValueError):
33
+ return False
34
+ good = sign(secret, body, t).split("v1=")[1]
35
+ return abs(now - t) <= TOLERANCE and hmac.compare_digest(good.encode(), got.encode())
36
+
37
+ # Direct raw hex HMAC
38
+ expected = hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
39
+ got = header.replace("sha256=", "").strip()
40
+ return hmac.compare_digest(expected.encode(), got.encode())
41
+
42
+
43
+ def _text(ev: dict, field: str) -> str:
44
+ value = ev.get(field)
45
+ if not isinstance(value, str) or not value.strip():
46
+ raise ApiError(400, "bad_request", f"'{field}' is required")
47
+ return value.strip()
48
+
49
+
50
+ def _int(ev: dict, field: str, optional: bool = False) -> int | None:
51
+ value = ev.get(field)
52
+ if value is None and optional:
53
+ return None
54
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
55
+ raise ApiError(400, "bad_request", f"'{field}' must be a unix time in seconds")
56
+ return value
57
+
58
+
59
+ def _licence(conn: Any, provider: str, ev: dict) -> Any:
60
+ row = conn.execute(
61
+ "SELECT * FROM licenses WHERE provider=? AND provider_ref=?", (provider, _text(ev, "ref"))
62
+ ).fetchone()
63
+ if row is None:
64
+ raise ApiError(409, "unknown_subscription", "no such subscription yet; retry later")
65
+ return row
66
+
67
+
68
+ def _started(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
69
+ start = _int(ev, "period_start", optional=True) or now
70
+ end = _int(ev, "period_end", optional=True)
71
+ plan = _text(ev, "plan")
72
+ ref = _text(ev, "ref")
73
+ email = _text(ev, "email")
74
+
75
+ row = conn.execute(
76
+ "SELECT * FROM licenses WHERE provider=? AND provider_ref=?", (provider, ref)
77
+ ).fetchone()
78
+ if row is None:
79
+ aid = accounts.account_for(conn, email, now)
80
+ lid, key = accounts.create_license(
81
+ conn, aid, plan, now, cfg, end, provider, ref, renews=True
82
+ )
83
+ info = {"email": email, "plan": plan, "key": key}
84
+ accounts.outbox_add(conn, aid, "license_key", info, now)
85
+ row = conn.execute("SELECT * FROM licenses WHERE id=?", (lid,)).fetchone()
86
+
87
+ accounts.start_period(conn, row, start, end, now, cfg)
88
+ return {"license": row["id"]}
89
+
90
+
91
+ def _renewed(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
92
+ row = _licence(conn, provider, ev)
93
+ start = _int(ev, "period_start", optional=True) or now
94
+ end = _int(ev, "period_end", optional=True)
95
+ conn.execute("UPDATE licenses SET status='active', period_end=? WHERE id=?", (end, row["id"]))
96
+ accounts.start_period(conn, row, start, end, now, cfg)
97
+ return {"license": row["id"]}
98
+
99
+
100
+ def _plan_changed(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
101
+ row = _licence(conn, provider, ev)
102
+ plan = _text(ev, "plan")
103
+ if plan not in cfg.plans:
104
+ raise ApiError(400, "unknown_plan", f"unknown plan '{plan}'")
105
+ conn.execute("UPDATE licenses SET plan=? WHERE id=?", (plan, row["id"]))
106
+ return {"license": row["id"]}
107
+
108
+
109
+ def _status(status: str):
110
+ def run(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
111
+ row = _licence(conn, provider, ev)
112
+ conn.execute("UPDATE licenses SET status=? WHERE id=?", (status, row["id"]))
113
+ return {"license": row["id"]}
114
+
115
+ return run
116
+
117
+
118
+ def _topup(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
119
+ pack = _text(ev, "pack")
120
+ if pack not in cfg.packs:
121
+ raise ApiError(400, "unknown_pack", f"unknown pack '{pack}'")
122
+ aid = accounts.account_for(conn, _text(ev, "email"), now)
123
+ expires = now + cfg.topup_days * 86400 if cfg.topup_days else None
124
+ ledger.grant(
125
+ conn, aid, "topup", cfg.packs[pack], now, expires, f"topup:{provider}:{_text(ev, 'id')}"
126
+ )
127
+ return {"account": aid}
128
+
129
+
130
+ HANDLERS: dict[str, Callable] = {
131
+ "subscription.started": _started,
132
+ "checkout.completed": _started,
133
+ "subscription.renewed": _renewed,
134
+ "subscription.plan_changed": _plan_changed,
135
+ "subscription.canceled": _status("canceled"),
136
+ "subscription.cancelled": _status("canceled"),
137
+ "subscription.past_due": _status("past_due"),
138
+ "subscription.expired": _status("revoked"),
139
+ "topup.paid": _topup,
140
+ }
141
+
142
+
143
+ def apply(conn: Any, provider: str, ev: dict, now: int, cfg: Config) -> dict:
144
+ """Apply one event exactly once; repeated event IDs are safely ignored."""
145
+ event_id = _text(ev, "id")
146
+ event_type = _text(ev, "type")
147
+ handler = HANDLERS.get(event_type)
148
+ if handler is None:
149
+ raise ApiError(400, "unknown_event", f"unknown event type '{event_type}'")
150
+ fresh = conn.execute(
151
+ "INSERT OR IGNORE INTO webhook_events(provider, event_id, received_at) VALUES (?,?,?)",
152
+ (provider, event_id, now),
153
+ )
154
+ if not fresh.rowcount:
155
+ return {"duplicate": True}
156
+ return handler(conn, provider, ev, now, cfg)
requirements.txt CHANGED
@@ -73,3 +73,6 @@ google-auth-httplib2>=0.2.0
73
  google-auth-oauthlib>=1.2.0
74
  isodate>=0.6.1
75
  youtube-transcript-api>=0.6.2
 
 
 
 
73
  google-auth-oauthlib>=1.2.0
74
  isodate>=0.6.1
75
  youtube-transcript-api>=0.6.2
76
+
77
+ # === FL-MCP Database Persistence (PostgreSQL for external DB) ===
78
+ psycopg2-binary>=2.9.9
tests/test_flmcp.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for FL-MCP Licensing, Credit Ledger, and Webhook APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import secrets
7
+ import tempfile
8
+ import time
9
+ import pytest
10
+ from fastapi.testclient import TestClient
11
+
12
+ from app.main import app
13
+ from app.services.flmcp import keys, webhooks
14
+ from app.services.flmcp.db import DB
15
+ from app.services.flmcp.plans import load
16
+
17
+
18
+ @pytest.fixture
19
+ def temp_db(monkeypatch):
20
+ fd, path = tempfile.mkstemp(suffix=".db")
21
+ os.close(fd)
22
+ monkeypatch.setenv("FLMCP_DB", path)
23
+ monkeypatch.setenv("FLMCP_ADMIN_TOKEN", "test-admin-secret-token")
24
+ monkeypatch.setenv("FLMCP_WEBHOOK_SECRETS", "stripe=stripe-test-secret,lemonsqueezy=lemon-secret")
25
+ # Initialize schema
26
+ db = DB(path)
27
+ yield db
28
+ try:
29
+ os.remove(path)
30
+ except OSError:
31
+ pass
32
+
33
+
34
+ @pytest.fixture
35
+ def client(temp_db):
36
+ return TestClient(app)
37
+
38
+
39
+ def test_keys_generation_and_validation():
40
+ key = keys.new_key()
41
+ assert key.startswith("FLMCP-")
42
+ normalized = keys.normalize(key)
43
+ assert normalized is not None
44
+ assert len(normalized) == 20
45
+
46
+ # Mistyped character fails checksum
47
+ chars = list(key)
48
+ chars[-1] = "A" if chars[-1] != "A" else "B"
49
+ bad_key = "".join(chars)
50
+ assert keys.normalize(bad_key) is None
51
+
52
+ # Crockford normalization (O -> 0, I -> 1, L -> 1)
53
+ norm = keys.normalize("flmcp-01111-23456-789ab-cdefg")
54
+ assert norm is not None or keys.normalize(key.lower().replace("-", "")) is not None
55
+
56
+
57
+ def test_user_trial_generation(client):
58
+ res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "producer@test.com", "device_name": "Studio-1"})
59
+ assert res.status_code == 200
60
+ data = res.json()
61
+ assert "key" in data
62
+ assert data["plan"] == "trial"
63
+ assert data["balance"] == 15
64
+ assert data["key"].startswith("FLMCP-")
65
+
66
+
67
+ def test_activate_device_and_account_status(client):
68
+ # 1. Create trial
69
+ t_res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "musician@flmcp.io"})
70
+ key = t_res.json()["key"]
71
+
72
+ # 2. Activate via /api/v1/flmcp/activate
73
+ act_res = client.post(
74
+ "/api/v1/flmcp/activate",
75
+ json={"license_key": key, "device_name": "Desktop-Win11", "device_id": "hw-uuid-1"},
76
+ )
77
+ assert act_res.status_code == 200
78
+ act_data = act_res.json()
79
+ assert "token" in act_data
80
+ assert "device_token" in act_data
81
+ token = act_data["token"]
82
+ assert act_data["balance"] == 15
83
+ assert act_data["plan"] == "trial"
84
+
85
+ # 3. Query account
86
+ acc_res = client.get("/api/v1/flmcp/account", headers={"Authorization": f"Bearer {token}"})
87
+ assert acc_res.status_code == 200
88
+ acc_data = acc_res.json()
89
+ assert acc_data["balance"] == 15
90
+ assert len(acc_data["devices"]) == 1
91
+ assert acc_data["devices"][0]["name"] == "Desktop-Win11"
92
+
93
+
94
+ def test_seat_limit_and_replace(client):
95
+ # Trial plan only allows 1 device seat
96
+ t_res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "producer2@flmcp.io"})
97
+ key = t_res.json()["key"]
98
+
99
+ # First device succeeds
100
+ r1 = client.post(
101
+ "/api/v1/flmcp/activate",
102
+ json={"key": key, "name": "Device-1", "device_id": "dev-1"},
103
+ )
104
+ assert r1.status_code == 200
105
+
106
+ # Second device without replace gives 409
107
+ r2 = client.post(
108
+ "/api/v1/flmcp/activate",
109
+ json={"key": key, "name": "Device-2", "device_id": "dev-2"},
110
+ )
111
+ assert r2.status_code == 409
112
+ prob = r2.json()
113
+ assert prob["code"] == "device_limit"
114
+ assert len(prob["devices"]) == 1
115
+
116
+ # Second device with replace succeeds
117
+ r3 = client.post(
118
+ "/api/v1/flmcp/activate",
119
+ json={"key": key, "name": "Device-2", "device_id": "dev-2", "replace": "Device-1"},
120
+ )
121
+ assert r3.status_code == 200
122
+ assert "token" in r3.json()
123
+
124
+
125
+ def test_credit_reservation_settlement_and_idempotency(client):
126
+ t_res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "credit_test@flmcp.io"})
127
+ key = t_res.json()["key"]
128
+ token = client.post(
129
+ "/v1/activate",
130
+ json={"key": key, "name": "Audio-Workstation", "device_id": "audio-pc"},
131
+ ).json()["token"]
132
+
133
+ # Starting balance is 15
134
+ idem = secrets.token_hex(16)
135
+ # produce.compose costs 5, mix.balance costs 2 (total 7)
136
+ res_hold = client.post(
137
+ "/api/v1/flmcp/credits/reserve",
138
+ json={"ops": ["produce.compose", "mix.balance"], "idem": idem},
139
+ headers={"Authorization": f"Bearer {token}"},
140
+ )
141
+ assert res_hold.status_code == 200
142
+ hold_data = res_hold.json()
143
+ rid = hold_data["id"]
144
+ assert hold_data["cost"] == 7
145
+ assert hold_data["balance"] == 8
146
+
147
+ # Retrying with same idem returns identical response (idempotent)
148
+ res_retry = client.post(
149
+ "/api/v1/flmcp/credits/reserve",
150
+ json={"ops": ["produce.compose", "mix.balance"], "idem": idem},
151
+ headers={"Authorization": f"Bearer {token}"},
152
+ )
153
+ assert res_retry.status_code == 200
154
+ assert res_retry.json()["id"] == rid
155
+
156
+ # Settle: only produce.compose (cost 5) succeeded, mix.balance (cost 2) failed and is refunded
157
+ res_settle = client.post(
158
+ f"/api/v1/flmcp/credits/{rid}/settle",
159
+ json={"done": ["produce.compose"]},
160
+ headers={"Authorization": f"Bearer {token}"},
161
+ )
162
+ assert res_settle.status_code == 200
163
+ settle_data = res_settle.json()
164
+ assert settle_data["charged"] == 5
165
+ assert settle_data["refunded"] == 2
166
+ # Balance should now be 15 - 5 = 10
167
+ assert settle_data["balance"] == 10
168
+
169
+
170
+ def test_insufficient_credits(client):
171
+ t_res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "poor_user@flmcp.io"})
172
+ key = t_res.json()["key"]
173
+ token = client.post(
174
+ "/api/v1/flmcp/activate",
175
+ json={"key": key, "name": "PC", "device_id": "pc-1"},
176
+ ).json()["token"]
177
+
178
+ # Attempt to reserve 20 credits when only 15 exist
179
+ # 4 * produce.compose = 20
180
+ # Ops must be distinct names in reserve API; but we can test with large op or multiple holds
181
+ idem1 = secrets.token_hex(16)
182
+ r1 = client.post(
183
+ "/api/v1/flmcp/credits/reserve",
184
+ json={"ops": ["produce.compose", "produce.flp", "mix.balance"], "idem": idem1},
185
+ headers={"Authorization": f"Bearer {token}"},
186
+ )
187
+ # 5 + 3 + 2 = 10 held; balance is 5
188
+ assert r1.status_code == 200
189
+ rid1 = r1.json()["id"]
190
+ client.post(
191
+ f"/api/v1/flmcp/credits/{rid1}/settle",
192
+ json={"done": ["produce.compose", "produce.flp", "mix.balance"]},
193
+ headers={"Authorization": f"Bearer {token}"},
194
+ )
195
+
196
+ # Now balance is 5; requesting 5+3=8 should fail with 402
197
+ idem2 = secrets.token_hex(16)
198
+ r2 = client.post(
199
+ "/api/v1/flmcp/credits/reserve",
200
+ json={"ops": ["produce.compose", "produce.flp"], "idem": idem2},
201
+ headers={"Authorization": f"Bearer {token}"},
202
+ )
203
+ assert r2.status_code == 402
204
+ err = r2.json()
205
+ assert err["code"] == "insufficient_credits"
206
+ assert "topup_url" in err
207
+
208
+
209
+ def test_device_self_revoke(client):
210
+ t_res = client.post("/api/v1/flmcp/user/generate-trial", json={"email": "revoker@flmcp.io"})
211
+ key = t_res.json()["key"]
212
+ token = client.post(
213
+ "/api/v1/flmcp/activate",
214
+ json={"key": key, "name": "Studio-Laptop", "device_id": "laptop-1"},
215
+ ).json()["token"]
216
+
217
+ rev_res = client.post("/api/v1/flmcp/devices/self/revoke", headers={"Authorization": f"Bearer {token}"})
218
+ assert rev_res.status_code == 204
219
+
220
+ # Using token after revocation fails with 401
221
+ acc = client.get("/api/v1/flmcp/account", headers={"Authorization": f"Bearer {token}"})
222
+ assert acc.status_code == 401
223
+
224
+
225
+ def test_webhook_payment_provisioning(client):
226
+ now = int(time.time())
227
+ secret = "stripe-test-secret"
228
+ payload = {
229
+ "id": "evt_test_checkout_123",
230
+ "type": "checkout.completed",
231
+ "email": "paid_customer@crowncode.studio",
232
+ "plan": "pro",
233
+ "ref": "sub_stripe_abc123",
234
+ "period_start": now,
235
+ "period_end": now + 30 * 86400,
236
+ }
237
+ body_bytes = str(payload).replace("'", '"').encode("utf-8")
238
+ sig = webhooks.sign(secret, body_bytes, now)
239
+
240
+ res = client.post(
241
+ "/api/v1/flmcp/webhooks/stripe",
242
+ content=body_bytes,
243
+ headers={"Content-Type": "application/json", "X-Signature": sig},
244
+ )
245
+ assert res.status_code == 200
246
+ assert "license" in res.json()
247
+
248
+ # User lookup by email finds pro license with 300 credits
249
+ lookup = client.post("/api/v1/flmcp/user/lookup", json={"email": "paid_customer@crowncode.studio"})
250
+ assert lookup.status_code == 200
251
+ data = lookup.json()
252
+ assert data["plan"] == "pro"
253
+ assert data["balance"] == 300
254
+ assert data["seats_allowed"] == 2