"""Small same-origin JSON API. Run behind Apache/HTTPS in production.""" import hashlib import hmac import ipaddress import json import logging import os import re import secrets import sqlite3 import time from dataclasses import dataclass from contextlib import contextmanager from http.cookies import SimpleCookie from pathlib import Path from urllib.parse import urlsplit LOG = logging.getLogger("amnesia.licensing") COOKIE = "amnesia_session" ROOT = Path(__file__).resolve().parents[1] USERNAME = re.compile(r"[a-zA-Z0-9_]{3,24}\Z") HWID = re.compile(r"[a-fA-F0-9]{64}\Z") @dataclass class Settings: data_dir: Path origin: str = "http://127.0.0.1:5173" secure_cookies: bool = False allow_local_setup: bool = False session_seconds: int = 43200 client_seconds: int = 900 rate_limit: bool = True allow_loopback_origins: bool = False @classmethod def environment(cls): origin = os.environ.get("AMNESIA_ORIGIN", "http://127.0.0.1:5173").rstrip("/") if urlsplit(origin).scheme not in ("http", "https") or not urlsplit(origin).netloc: raise ValueError("AMNESIA_ORIGIN must be a full http(s) origin") return cls(Path(os.environ.get("AMNESIA_DATA", str(ROOT / "data"))), origin, origin.startswith("https://"), False) SCHEMA = """ CREATE TABLE IF NOT EXISTS accounts ( uid INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, username_key TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user' CHECK(role IN ('user','admin')), enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL, hwid_hash TEXT, device_name TEXT, bound_at INTEGER, last_seen INTEGER ); CREATE TABLE IF NOT EXISTS licenses ( id TEXT PRIMARY KEY, key_hash TEXT NOT NULL UNIQUE, key_hint TEXT NOT NULL, label TEXT NOT NULL, duration_days INTEGER, status TEXT NOT NULL DEFAULT 'issued', account_uid INTEGER REFERENCES accounts(uid), created_at INTEGER NOT NULL, activated_at INTEGER, expires_at INTEGER ); CREATE TABLE IF NOT EXISTS sessions ( token_hash TEXT PRIMARY KEY, account_uid INTEGER NOT NULL REFERENCES accounts(uid), csrf TEXT NOT NULL, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS client_tokens ( token_hash TEXT PRIMARY KEY, account_uid INTEGER NOT NULL REFERENCES accounts(uid), license_id TEXT NOT NULL REFERENCES licenses(id), hwid_hash TEXT NOT NULL, expires_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS reset_requests ( account_uid INTEGER PRIMARY KEY REFERENCES accounts(uid), reason TEXT NOT NULL, requested_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS audit ( id INTEGER PRIMARY KEY AUTOINCREMENT, actor_uid INTEGER REFERENCES accounts(uid), action TEXT NOT NULL, subject TEXT NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS limits ( identity TEXT PRIMARY KEY, count INTEGER NOT NULL, expires_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS licenses_owner ON licenses(account_uid); CREATE INDEX IF NOT EXISTS sessions_owner ON sessions(account_uid); CREATE INDEX IF NOT EXISTS audit_time ON audit(id DESC); PRAGMA user_version=1; """ class ApiError(Exception): def __init__(self, status, message, code="request_failed"): self.status, self.message, self.code = status, message, code def password_hash(password): salt = secrets.token_hex(16) digest = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), 600000) return f"pbkdf2_sha256$600000${salt}${digest.hex()}" def password_matches(password, encoded): try: _, iterations, salt, expected = encoded.split("$") actual = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), int(iterations)).hex() return hmac.compare_digest(actual, expected) except (ValueError, TypeError): return False def text(body, name, minimum=1, maximum=128): value = body.get(name) if not isinstance(value, str) or not minimum <= len(value) <= maximum: raise ApiError(400, f"{name.replace('_', ' ')} must be {minimum}–{maximum} characters", "invalid_input") return value def credentials(body): username = text(body, "username", 3, 24) if not USERNAME.fullmatch(username): raise ApiError(400, "account names use letters, numbers and underscores", "invalid_input") return username, text(body, "password", 12, 128) class Application: def __init__(self, settings): self.settings = settings settings.data_dir.mkdir(parents=True, exist_ok=True, mode=0o700) secret_path = settings.data_dir / "hwid.secret" try: with secret_path.open("xb") as output: os.chmod(secret_path, 0o600) output.write(secrets.token_bytes(32)) except FileExistsError: pass self.secret = secret_path.read_bytes() if len(self.secret) != 32: raise ValueError("hwid.secret must contain 32 bytes; restore it from backup") self.database = settings.data_dir / "licensing.sqlite3" with self.connect() as db: db.execute("PRAGMA journal_mode=WAL") db.executescript(SCHEMA) os.chmod(self.database, 0o600) self.dummy_hash = password_hash(secrets.token_urlsafe(32)) @contextmanager def connect(self): db = sqlite3.connect(self.database, timeout=10) db.row_factory = sqlite3.Row db.execute("PRAGMA foreign_keys=ON") try: with db: yield db finally: db.close() def digest(self, namespace, value): return hmac.new(self.secret, (namespace + ":" + value).encode(), hashlib.sha256).hexdigest() def origin_allowed(self, origin): if origin == self.settings.origin: return True if not self.settings.allow_loopback_origins: return False try: expected, incoming = urlsplit(self.settings.origin), urlsplit(origin) loopback = {"localhost", "127.0.0.1", "::1"} return (expected.scheme == incoming.scheme == "http" and expected.hostname in loopback and incoming.hostname in loopback and (expected.port or 80) == (incoming.port or 80) and not incoming.username and not incoming.password and not incoming.path and not incoming.query and not incoming.fragment) except ValueError: return False @staticmethod def token_hash(token): return hashlib.sha256(token.encode()).hexdigest() def audit(self, db, actor, action, subject): db.execute("INSERT INTO audit(actor_uid,action,subject,created_at) VALUES(?,?,?,?)", (actor, action, str(subject), int(time.time()))) def create_account(self, db, username, password, role="user"): try: cursor = db.execute("INSERT INTO accounts(username,username_key,password_hash,role,created_at) VALUES(?,?,?,?,?)", (username, username.lower(), password_hash(password), role, int(time.time()))) except sqlite3.IntegrityError: raise ApiError(409, "that account name is unavailable", "name_taken") self.audit(db, cursor.lastrowid, "account.created", cursor.lastrowid) return db.execute("SELECT * FROM accounts WHERE uid=?", (cursor.lastrowid,)).fetchone() def account_view(self, account): return {key: account[key] for key in ("uid", "username", "role", "created_at", "enabled", "device_name", "bound_at", "last_seen")} | {"hwid_bound": bool(account["hwid_hash"])} @staticmethod def license_view(license): value = {key: license[key] for key in ("id", "key_hint", "label", "duration_days", "status", "account_uid", "created_at", "activated_at", "expires_at")} if value["status"] == "active" and value["expires_at"] is not None and value["expires_at"] <= time.time(): value["status"] = "expired" return value def active_license(self, db, uid): return db.execute("SELECT * FROM licenses WHERE account_uid=? AND status='active' AND (expires_at IS NULL OR expires_at>?) ORDER BY expires_at IS NULL DESC, expires_at DESC LIMIT 1", (uid, int(time.time()))).fetchone() def session(self, db, environ): cookies = SimpleCookie() try: cookies.load(environ.get("HTTP_COOKIE", "")) except Exception: return None, None token = cookies.get(COOKIE) if not token or len(token.value) > 128: return None, None session = db.execute("SELECT * FROM sessions WHERE token_hash=? AND expires_at>?", (self.token_hash(token.value), int(time.time()))).fetchone() account = db.execute("SELECT * FROM accounts WHERE uid=? AND enabled=1", (session["account_uid"],)).fetchone() if session else None return session, account def cookie(self, token, lifetime): result = f"{COOKIE}={token}; Path=/api; HttpOnly; SameSite=Strict; Max-Age={lifetime}" return result + ("; Secure" if self.settings.secure_cookies else "") def login(self, db, account): now = int(time.time()) token, csrf = secrets.token_urlsafe(32), secrets.token_urlsafe(32) db.execute("DELETE FROM sessions WHERE expires_at<=?", (now,)) db.execute("DELETE FROM client_tokens WHERE expires_at<=?", (now,)) db.execute("INSERT INTO sessions VALUES(?,?,?,?,?)", (self.token_hash(token), account["uid"], csrf, now + self.settings.session_seconds, now)) db.execute("DELETE FROM sessions WHERE account_uid=? AND token_hash NOT IN (SELECT token_hash FROM sessions WHERE account_uid=? ORDER BY created_at DESC,rowid DESC LIMIT 5)", (account["uid"], account["uid"])) return {"account": self.account_view(account), "csrf": csrf}, [("Set-Cookie", self.cookie(token, self.settings.session_seconds))] def limit(self, db, identity, maximum, seconds): if not self.settings.rate_limit: return now = int(time.time()) key = self.digest("rate", identity) db.execute("DELETE FROM limits WHERE expires_at<=?", (now,)) db.execute("INSERT INTO limits VALUES(?,1,?) ON CONFLICT(identity) DO UPDATE SET count=count+1", (key, now + seconds)) count = db.execute("SELECT count FROM limits WHERE identity=?", (key,)).fetchone()[0] if count > maximum: raise ApiError(429, "too many attempts; try again shortly", "rate_limited") def __call__(self, environ, start_response): extra = [] try: method, path = environ.get("REQUEST_METHOD", "GET"), environ.get("PATH_INFO", "/") if len(path) > 512: raise ApiError(414, "request path is too long") if method not in ("GET", "POST"): raise ApiError(405, "method not allowed") body = {} if method == "POST": if environ.get("CONTENT_TYPE", "").split(";")[0] != "application/json": raise ApiError(415, "send application/json") try: length = int(environ.get("CONTENT_LENGTH", "0")) except ValueError: raise ApiError(400, "invalid request length") if length <= 0 or length > 16384: raise ApiError(413, "request body must be 1–16384 bytes") try: body = json.loads(environ["wsgi.input"].read(length)) except (ValueError, UnicodeDecodeError): raise ApiError(400, "invalid JSON") if not isinstance(body, dict): raise ApiError(400, "send a JSON object") if not path.startswith("/api/client/") and not self.origin_allowed(environ.get("HTTP_ORIGIN", "")): raise ApiError(403, "request origin rejected", "origin_rejected") with self.connect() as db: # Commit rate counters even when an authentication request fails. self.limit(db, "all:" + environ.get("REMOTE_ADDR", "unknown"), 360, 60) if method == "POST" and path in ("/api/auth/login", "/api/auth/register", "/api/setup", "/api/client/activate"): self.limit(db, "auth:" + environ.get("REMOTE_ADDR", "unknown"), 12, 60) if isinstance(body.get("username"), str): self.limit(db, "name:" + body["username"].lower()[:128], 30, 300) db.commit() db.execute("BEGIN IMMEDIATE" if method == "POST" else "BEGIN") result, extra = self.route(db, environ, method, path, body) status = 200 except ApiError as error: status, result = error.status, {"error": error.message, "code": error.code} except (sqlite3.Error, OSError): LOG.exception("licensing request failed") status, result = 503, {"error": "service temporarily unavailable", "code": "service_unavailable"} except Exception: LOG.exception("unexpected licensing error") status, result = 500, {"error": "request could not be completed", "code": "internal_error"} payload = json.dumps(result, separators=(",", ":")).encode() names = {200:"OK",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable"} headers = [("Content-Type", "application/json; charset=utf-8"), ("Content-Length", str(len(payload))), ("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"), ("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")] + extra if status == 429: headers.append(("Retry-After", "60")) start_response(f"{status} {names.get(status,'Error')}", headers) return [payload] def route(self, db, environ, method, path, body): if method == "GET" and path == "/api/health": return {"status": "online", "service": "amnesia licensing"}, [] session, account = self.session(db, environ) if method == "GET" and path == "/api/session": exists = db.execute("SELECT 1 FROM accounts WHERE role='admin' LIMIT 1").fetchone() return {"account": self.account_view(account) if account else None, "csrf": session["csrf"] if account else None, "setup_required": self.settings.allow_local_setup and not exists}, [] if method == "POST" and path == "/api/setup": try: local = ipaddress.ip_address(environ.get("REMOTE_ADDR", "")).is_loopback except ValueError: local = False if not self.settings.allow_local_setup or not local or db.execute("SELECT 1 FROM accounts LIMIT 1").fetchone(): raise ApiError(403, "initial setup is unavailable") username, password = credentials(body) return self.login(db, self.create_account(db, username, password, "admin")) if method == "POST" and path in ("/api/auth/register", "/api/auth/login"): username, password = credentials(body) if path.endswith("register"): if not db.execute("SELECT 1 FROM accounts WHERE role='admin' LIMIT 1").fetchone(): raise ApiError(403, "registration is not available yet") return self.login(db, self.create_account(db, username, password)) candidate = db.execute("SELECT * FROM accounts WHERE username_key=?", (username.lower(),)).fetchone() valid = password_matches(password, candidate["password_hash"] if candidate else self.dummy_hash) if not valid or not candidate or not candidate["enabled"]: raise ApiError(401, "account name or password is incorrect", "invalid_credentials") return self.login(db, candidate) if method == "POST" and path.startswith("/api/client/"): return self.client(db, environ, path, body), [] if not account: raise ApiError(401, "sign in to continue", "sign_in_required") if method == "POST" and not hmac.compare_digest(environ.get("HTTP_X_CSRF_TOKEN", ""), session["csrf"]): raise ApiError(403, "session check failed; refresh and try again", "csrf_failed") uid = account["uid"] if method == "POST" and path == "/api/auth/logout": db.execute("DELETE FROM sessions WHERE token_hash=?", (session["token_hash"],)) return {"ok": True}, [("Set-Cookie", self.cookie("", 0))] if method == "GET" and path == "/api/account": licenses = [self.license_view(row) for row in db.execute("SELECT * FROM licenses WHERE account_uid=? ORDER BY created_at DESC", (uid,))] reset = db.execute("SELECT reason,requested_at FROM reset_requests WHERE account_uid=?", (uid,)).fetchone() return {"account": self.account_view(account), "licenses": licenses, "reset_request": dict(reset) if reset else None}, [] if method == "POST" and path == "/api/licenses/redeem": key = text(body,"key",10,128).strip().upper() license = db.execute("SELECT * FROM licenses WHERE key_hash=?", (self.digest("license", key),)).fetchone() if not license or license["status"] != "issued": raise ApiError(400, "that license key is invalid or already used", "invalid_license") now = int(time.time()) expires = now + license["duration_days"] * 86400 if license["duration_days"] else None db.execute("UPDATE licenses SET account_uid=?,status='active',activated_at=?,expires_at=? WHERE id=?", (uid,now,expires,license["id"])) self.audit(db,uid,"license.redeemed",license["id"]) return {"ok": True}, [] if method == "POST" and path == "/api/account/password": if not password_matches(text(body,"current_password",1,128), account["password_hash"]): raise ApiError(400, "current password is incorrect") password = text(body,"new_password",12,128) db.execute("UPDATE accounts SET password_hash=? WHERE uid=?", (password_hash(password),uid)) db.execute("DELETE FROM sessions WHERE account_uid=?", (uid,)) db.execute("DELETE FROM client_tokens WHERE account_uid=?", (uid,)) self.audit(db,uid,"password.changed",uid) return {"ok":True}, [("Set-Cookie",self.cookie("",0))] if method == "POST" and path == "/api/account/hwid-reset": if not account["hwid_hash"]: raise ApiError(409,"no device is linked to this account") reason = text(body,"reason",5,240).strip() if len(reason)<5: raise ApiError(400,"include a reason of at least 5 characters") db.execute("INSERT INTO reset_requests VALUES(?,?,?) ON CONFLICT(account_uid) DO UPDATE SET reason=excluded.reason, requested_at=excluded.requested_at", (uid,reason,int(time.time()))) self.audit(db,uid,"hwid.reset_requested",uid) return {"ok":True}, [] if path.startswith("/api/admin/"): if account["role"] != "admin": raise ApiError(403,"administrator access required") return self.admin(db,account,method,path,body), [] raise ApiError(404,"endpoint not found") def client(self, db, environ, path, body): fingerprint = text(body,"hwid",64,64) if not HWID.fullmatch(fingerprint): raise ApiError(400,"hwid must be a SHA-256 fingerprint","invalid_hwid") hardware = self.digest("hwid",fingerprint.lower()) now = int(time.time()) if path == "/api/client/activate": username,password = credentials(body) account = db.execute("SELECT * FROM accounts WHERE username_key=?", (username.lower(),)).fetchone() valid = password_matches(password,account["password_hash"] if account else self.dummy_hash) if not valid or not account or not account["enabled"]: raise ApiError(401,"account name or password is incorrect","invalid_credentials") license = self.active_license(db,account["uid"]) if not license: raise ApiError(403,"an active license is required","license_required") if account["hwid_hash"] and not hmac.compare_digest(hardware,account["hwid_hash"]): raise ApiError(403,"this account is linked to another device","hwid_mismatch") device_name = text(body,"device_name",1,48) if "device_name" in body else "linked device" db.execute("UPDATE accounts SET hwid_hash=?,device_name=?,bound_at=COALESCE(bound_at,?),last_seen=? WHERE uid=?", (hardware,device_name,now,now,account["uid"])) token = secrets.token_urlsafe(32) expires = min(now+self.settings.client_seconds, license["expires_at"] or now+self.settings.client_seconds) db.execute("DELETE FROM client_tokens WHERE account_uid=? OR expires_at<=?", (account["uid"],now)) db.execute("INSERT INTO client_tokens VALUES(?,?,?,?,?)", (self.token_hash(token),account["uid"],license["id"],hardware,expires)) self.audit(db,account["uid"],"device.activated",license["id"]) return {"token":token,"expires_at":expires,"server_time":now,"recheck_after":60,"account":{"uid":account["uid"],"username":account["username"]},"license":self.license_view(license)} if path in ("/api/client/verify", "/api/client/logout"): auth = environ.get("HTTP_AUTHORIZATION", "") token = auth[7:] if auth.startswith("Bearer ") else "" if not 20 <= len(token) <= 128: raise ApiError(401,"valid client token required","invalid_token") record = db.execute("SELECT * FROM client_tokens WHERE token_hash=? AND expires_at>?", (self.token_hash(token),now)).fetchone() if not record: raise ApiError(401,"client session expired; sign in again","invalid_token") account = db.execute("SELECT * FROM accounts WHERE uid=? AND enabled=1", (record["account_uid"],)).fetchone() license = db.execute("SELECT * FROM licenses WHERE id=? AND status='active' AND (expires_at IS NULL OR expires_at>?)", (record["license_id"],now)).fetchone() if not account or not license: raise ApiError(403,"access is no longer active","access_revoked") if not account["hwid_hash"] or not hmac.compare_digest(hardware,record["hwid_hash"]) or not hmac.compare_digest(hardware,account["hwid_hash"]): raise ApiError(403,"device does not match this session","hwid_mismatch") if path.endswith("logout"): db.execute("DELETE FROM client_tokens WHERE token_hash=?", (record["token_hash"],)) return {"ok":True} if "renew" in body and type(body["renew"]) is not bool: raise ApiError(400,"renew must be true or false") expires = record["expires_at"] if body.get("renew"): expires = min(now+self.settings.client_seconds, license["expires_at"] or now+self.settings.client_seconds) db.execute("UPDATE client_tokens SET expires_at=? WHERE token_hash=?", (expires,record["token_hash"])) db.execute("UPDATE accounts SET last_seen=? WHERE uid=?", (now,account["uid"])) return {"valid":True,"expires_at":expires,"server_time":now,"recheck_after":60,"account":{"uid":account["uid"],"username":account["username"]},"license":self.license_view(license)} raise ApiError(404,"endpoint not found") def admin(self, db, account, method, path, body): uid = account["uid"] if method == "GET" and path == "/api/admin/overview": counts = {"accounts":db.execute("SELECT count(*) FROM accounts").fetchone()[0],"active_licenses":db.execute("SELECT count(*) FROM licenses WHERE status='active' AND (expires_at IS NULL OR expires_at>?)",(int(time.time()),)).fetchone()[0],"issued_keys":db.execute("SELECT count(*) FROM licenses WHERE status='issued'").fetchone()[0],"reset_requests":db.execute("SELECT count(*) FROM reset_requests").fetchone()[0]} accounts = [self.account_view(row) for row in db.execute("SELECT * FROM accounts ORDER BY uid LIMIT 500")] licenses = [self.license_view(row) for row in db.execute("SELECT * FROM licenses ORDER BY created_at DESC,rowid DESC LIMIT 500")] resets = [dict(row) for row in db.execute("SELECT * FROM reset_requests ORDER BY requested_at")] audit = [dict(row) for row in db.execute("SELECT audit.*,accounts.username FROM audit LEFT JOIN accounts ON accounts.uid=audit.actor_uid ORDER BY id DESC LIMIT 100")] return {"counts":counts,"accounts":accounts,"licenses":licenses,"reset_requests":resets,"audit":audit} if method == "POST" and path == "/api/admin/licenses": label = text(body,"label",1,60).strip() if not label: raise ApiError(400,"a license label is required") days = body.get("duration_days") if days is not None and (type(days) is not int or not 1 <= days <= 3650): raise ApiError(400,"duration must be 1–3650 days, or null for lifetime") key = "AMN-" + "-".join(secrets.token_hex(4).upper() for _ in range(4)) identifier = secrets.token_hex(12) db.execute("INSERT INTO licenses(id,key_hash,key_hint,label,duration_days,created_at) VALUES(?,?,?,?,?,?)", (identifier,self.digest("license",key),"AMN-…-"+key[-8:],label,days,int(time.time()))) self.audit(db,uid,"license.issued",identifier) return {"key":key,"license":self.license_view(db.execute("SELECT * FROM licenses WHERE id=?",(identifier,)).fetchone())} match = re.fullmatch(r"/api/admin/licenses/([a-f0-9]{24})/revoke",path) if method == "POST" and match: if not db.execute("SELECT 1 FROM licenses WHERE id=?",(match[1],)).fetchone(): raise ApiError(404,"license not found") db.execute("UPDATE licenses SET status='revoked' WHERE id=?",(match[1],)) db.execute("DELETE FROM client_tokens WHERE license_id=?",(match[1],)) self.audit(db,uid,"license.revoked",match[1]) return {"ok":True} match = re.fullmatch(r"/api/admin/accounts/(\d+)/(reset-hwid|status)",path) if method == "POST" and match: target = int(match[1]) if not db.execute("SELECT 1 FROM accounts WHERE uid=?",(target,)).fetchone(): raise ApiError(404,"account not found") if match[2] == "reset-hwid": db.execute("UPDATE accounts SET hwid_hash=NULL,device_name=NULL,bound_at=NULL WHERE uid=?",(target,)) db.execute("DELETE FROM reset_requests WHERE account_uid=?",(target,)) self.audit(db,uid,"hwid.reset",target) else: if type(body.get("enabled")) is not bool: raise ApiError(400,"enabled must be true or false") if target == uid: raise ApiError(409,"you cannot disable your own administrator account") db.execute("UPDATE accounts SET enabled=? WHERE uid=?",(body["enabled"],target)) if not body["enabled"]: db.execute("DELETE FROM sessions WHERE account_uid=?",(target,)) self.audit(db,uid,"account.enabled" if body["enabled"] else "account.disabled",target) db.execute("DELETE FROM client_tokens WHERE account_uid=?",(target,)) return {"ok":True} raise ApiError(404,"endpoint not found") def create_app(): return Application(Settings.environment())