#!/usr/bin/env python3 """License guard for bookkeeping-ai-workbench (commercial distribution). Soft protection, by design: target buyers are non-technical agency owners. Model: 3-day free trial -> paid license key -> expiry lock. Key format: BKAW--- Plans: TRIAL30 (体验版30天) / SEAT (坐席月付) / YEAR (坐席年付) Buyer commands: python3 scripts/license_guard.py status python3 scripts/license_guard.py activate --key BKAW-XXXX-20261231-XXXXXXXX """ import hashlib import hmac import json import os import sys from datetime import date, datetime _SECRET = "bkaw-2026-license-secret-v1" FREE_TRIAL_DAYS = 3 STATE_DIR = os.environ.get( "BKAW_STATE_DIR", os.path.expanduser("~/.bookkeeping_ai_workbench") ) LICENSE_FILE = os.path.join(STATE_DIR, "license.json") TRIAL_FILE = os.path.join(STATE_DIR, "trial.json") PLANS = { "TRIAL30": "体验版(30天)", "SEAT": "坐席版(月付)", "YEAR": "坐席版(年付)", } PRICING_HINT = ( "定价:¥20 体验 30 天(可抵扣首月)|正式 ¥500/坐席/月|年付 ¥5000 送 2 个月" ) def _sig(plan: str, expiry: str) -> str: return hmac.new( _SECRET.encode(), f"{plan}:{expiry}".encode(), hashlib.sha256 ).hexdigest()[:8].upper() def validate_key(key: str): """Return dict(plan, plan_name, expires) if key is authentic, else None.""" parts = (key or "").strip().upper().split("-") if len(parts) != 4 or parts[0] != "BKAW": return None _, plan, expiry, sig = parts if plan not in PLANS or len(expiry) != 8 or not expiry.isdigit(): return None if not hmac.compare_digest(sig, _sig(plan, expiry)): return None try: exp = datetime.strptime(expiry, "%Y%m%d").date() except ValueError: return None return {"plan": plan, "plan_name": PLANS[plan], "expires": exp} def _read_json(path): try: with open(path, encoding="utf-8") as f: return json.load(f) except Exception: return None def _write_json(path, obj): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w", encoding="utf-8") as f: json.dump(obj, f, ensure_ascii=False) def _contact() -> str: return os.environ.get("BKAW_SELLER_CONTACT") or ( "加微信 Marco-8172 购买/续期激活码:¥20 用 30 天 / ¥500 每坐席每月" ) def activate(key: str) -> bool: info = validate_key(key) if not info: print("✗ 密钥无效,请核对后重试(注意大小写与连字符)。") return False if (info["expires"] - date.today()).days < 0: print(f"✗ 密钥已于 {info['expires']} 到期,{_contact()}") return False _write_json(LICENSE_FILE, {"key": key.strip().upper()}) left = (info["expires"] - date.today()).days print(f"✓ 激活成功:{info['plan_name']},有效期至 {info['expires']}(剩 {left} 天)") return True def status() -> None: lic = _read_json(LICENSE_FILE) if lic and lic.get("key"): info = validate_key(lic["key"]) if info: left = (info["expires"] - date.today()).days state = "有效" if left >= 0 else "已到期" print(f"授权状态:{info['plan_name']} · {state} · 有效期至 {info['expires']}") return trial = _read_json(TRIAL_FILE) if trial: first = datetime.strptime(trial["first_run"], "%Y-%m-%d").date() used = (date.today() - first).days print(f"授权状态:免费试用中 · 第 {min(used + 1, FREE_TRIAL_DAYS)}/{FREE_TRIAL_DAYS} 天") else: print("授权状态:未激活(首次运行任意脚本即开始 3 天免费试用)") print(PRICING_HINT) def require_license() -> None: """Called by every workbench script before doing real work.""" lic = _read_json(LICENSE_FILE) if lic and lic.get("key"): info = validate_key(lic["key"]) if info: left = (info["expires"] - date.today()).days if left >= 0: if left <= 7: print(f"[授权] {info['plan_name']} 剩 {left} 天到期,续费:{_contact()}") return print(f"[授权] 密钥已于 {info['expires']} 到期。") else: print("[授权] 本地密钥无效。") trial = _read_json(TRIAL_FILE) if not trial: trial = {"first_run": date.today().isoformat()} _write_json(TRIAL_FILE, trial) try: first = datetime.strptime(trial["first_run"], "%Y-%m-%d").date() except Exception: first = date.today() used = (date.today() - first).days if used < FREE_TRIAL_DAYS: print( f"[试用] 免费试用第 {used + 1}/{FREE_TRIAL_DAYS} 天。" f"¥20 得 30 天体验码,正式 ¥500/坐席/月。{_contact()}" ) return print("=" * 56) print("免费试用期已结束。") print(PRICING_HINT) print(f"购买后执行:python3 scripts/license_guard.py activate --key <你的密钥>") print(_contact()) print("=" * 56) sys.exit(2) if __name__ == "__main__": import argparse p = argparse.ArgumentParser(description="bookkeeping-ai-workbench 授权管理") sub = p.add_subparsers(dest="cmd", required=True) sub.add_parser("status", help="查看授权状态") a = sub.add_parser("activate", help="激活密钥") a.add_argument("--key", required=True) args = p.parse_args() if args.cmd == "status": status() elif args.cmd == "activate": sys.exit(0 if activate(args.key) else 1)