"""Edition / entitlement handling. Community is free forever. Enterprise is unlocked by a signed license key or a 30-day trial. Keys are HMAC-signed for this reference implementation; swap the signature for Ed25519 (public key in the app, private key in your license service) when you ship commercially. """ from __future__ import annotations import base64 import hashlib import hmac import json from datetime import datetime, timedelta, timezone from typing import Any, Dict, Iterable, List, Optional from . import config, db from .util import utcnow TRIAL_DAYS = 30 COMMUNITY_FEATURES = { "core", "bundled_modules", "rest_api", "local_insights", "forecasting", "what_if", "csv_export", } ENTERPRISE_FEATURES = COMMUNITY_FEATURES | { "custom_modules", "llm_copilot", "mcp_server", "unlimited_assets", "long_retention", "audit_export", "alert_webhooks", "priority_support", } FEATURE_LABELS = { "core": "Capacity dashboard", "bundled_modules": "All bundled integrations", "rest_api": "REST API & push ingestion", "local_insights": "Local capacity insights", "forecasting": "Forecasting & days-to-full", "what_if": "What-if simulator", "csv_export": "CSV export", "custom_modules": "Upload custom modules", "llm_copilot": "LLM copilot (OpenAI-compatible)", "mcp_server": "MCP server for AI agents", "unlimited_assets": "Unlimited assets", "long_retention": "400-day metric retention", "audit_export": "Audit log export", "alert_webhooks": "Alert webhooks", "priority_support": "Priority support", } COMMUNITY_LIMITS = {"assets": 40, "retention_days": 30} ENTERPRISE_LIMITS = {"assets": -1, "retention_days": 400} def _b64e(raw: bytes) -> str: return base64.urlsafe_b64encode(raw).decode().rstrip("=") def _b64d(value: str) -> bytes: return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) def _signing_key() -> bytes: return hashlib.sha256(("license:" + config.get_secret()).encode()).digest() def issue_key( customer: str, days: int = 365, assets: int = -1, features: Optional[Iterable[str]] = None, edition: str = "enterprise", ) -> str: payload = { "v": 1, "edition": edition, "customer": customer, "assets": int(assets), "features": sorted(features or ENTERPRISE_FEATURES), "issued": utcnow().isoformat(timespec="seconds"), "expires": (utcnow() + timedelta(days=days)).isoformat(timespec="seconds"), } body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode()) sig = hmac.new(_signing_key(), body.encode(), hashlib.sha256).digest() return f"HR1.{body}.{_b64e(sig)}" def verify_key(key: str) -> Optional[Dict[str, Any]]: try: prefix, body, signature = key.strip().split(".") if prefix != "HR1": return None expected = hmac.new(_signing_key(), body.encode(), hashlib.sha256).digest() if not hmac.compare_digest(_b64d(signature), expected): return None payload = json.loads(_b64d(body)) expires = datetime.fromisoformat(payload["expires"]) if expires.tzinfo is None: expires = expires.replace(tzinfo=timezone.utc) if expires < utcnow(): payload["expired"] = True return payload except (ValueError, KeyError, TypeError, json.JSONDecodeError): return None def activate(key: str) -> Dict[str, Any]: payload = verify_key(key) if not payload: raise ValueError("Invalid license key") if payload.get("expired"): raise ValueError("This license key has expired") if payload.get("edition") not in ("enterprise", "trial"): raise ValueError("Unsupported license edition") db.set_setting("license_key", key.strip()) db.set_setting("license_activated_at", utcnow().isoformat(timespec="seconds")) return payload def deactivate() -> None: db.set_setting("license_key", "") db.set_setting("license_activated_at", "") def start_trial() -> Dict[str, Any]: if db.get_setting("trial_started_at"): raise ValueError("A trial has already been used on this installation") db.set_setting("trial_started_at", utcnow().isoformat(timespec="seconds")) return status() def status() -> Dict[str, Any]: settings = db.settings_map() enterprise_mode = str(settings.get("enterprise_mode", "0") or "0").strip().lower() if enterprise_mode in ("1", "true", "yes", "on"): configured_retention = int(settings.get("retention_days", "30") or 30) return { "edition": "enterprise", "label": "Enterprise", "source": "admin", "valid": True, "admin_override": True, "features": sorted(ENTERPRISE_FEATURES), "limits": { "assets": -1, "retention_days": max(ENTERPRISE_LIMITS["retention_days"], configured_retention), }, "customer": "Administrator unlock", "expires": None, "days_left": None, } key = settings.get("license_key", "") trial_started = settings.get("trial_started_at", "") result: Dict[str, Any] = { "edition": "community", "label": "Community", "source": "community", "valid": True, "admin_override": False, "features": sorted(COMMUNITY_FEATURES), "limits": dict(COMMUNITY_LIMITS), "customer": None, "expires": None, "days_left": None, } if key: payload = verify_key(key) if payload and not payload.get("expired"): result.update( edition="enterprise", label="Enterprise", source="license", customer=payload.get("customer"), expires=payload.get("expires"), features=sorted(set(payload.get("features") or ENTERPRISE_FEATURES)), limits={ "assets": int(payload.get("assets", -1)), "retention_days": max( ENTERPRISE_LIMITS["retention_days"], int(settings.get("retention_days", "30") or 30), ), }, ) expires = datetime.fromisoformat(payload["expires"]) if expires.tzinfo is None: expires = expires.replace(tzinfo=timezone.utc) result["days_left"] = max(0, (expires - utcnow()).days) return result result["invalid_license"] = True if trial_started: try: started = datetime.fromisoformat(trial_started) if started.tzinfo is None: started = started.replace(tzinfo=timezone.utc) ends = started + timedelta(days=TRIAL_DAYS) left = (ends - utcnow()).days if ends > utcnow(): result.update( edition="trial", label="Enterprise trial", source="trial", customer="Trial", expires=ends.isoformat(timespec="seconds"), days_left=max(0, left), features=sorted(ENTERPRISE_FEATURES), limits={ "assets": -1, "retention_days": ENTERPRISE_LIMITS["retention_days"], }, ) return result result["trial_expired"] = True except ValueError: pass return result def has_feature(feature: str) -> bool: return feature in status()["features"] def retention_days() -> int: st = status() configured = int(db.get_setting("retention_days", "30") or 30) limit = int(st["limits"].get("retention_days", 30)) return max(7, min(configured, limit)) def asset_limit() -> int: return int(status()["limits"].get("assets", 40)) def edition_matrix() -> List[Dict[str, Any]]: grouped = [ ("Core capacity", ["core", "bundled_modules", "rest_api", "local_insights", "forecasting", "what_if", "csv_export"]), ("Scale & automation", ["custom_modules", "unlimited_assets", "long_retention", "alert_webhooks"]), ("AI & integration", ["mcp_server", "llm_copilot"]), ("Enterprise controls", ["audit_export", "priority_support"]), ] out = [] for group, features in grouped: out.append( { "group": group, "features": [ { "key": f, "label": FEATURE_LABELS.get(f, f), "community": f in COMMUNITY_FEATURES, "enterprise": f in ENTERPRISE_FEATURES, } for f in features ], } ) return out def _main() -> None: import argparse parser = argparse.ArgumentParser(description="Issue Headroom license keys") parser.add_argument("customer", nargs="?", default="Homelab") parser.add_argument("--days", type=int, default=365) parser.add_argument("--assets", type=int, default=-1) args = parser.parse_args() print(issue_key(args.customer, days=args.days, assets=args.assets)) if __name__ == "__main__": _main()