import os import sqlite3 from contextlib import closing from pathlib import Path from types import SimpleNamespace from Crypto.Random import get_random_bytes from flask import Flask from werkzeug.exceptions import HTTPException from werkzeug.security import generate_password_hash from backend.app.common.constants import LIFETIME from backend.app.common.errors import LedgerError from backend.app.common.utils import utc_now from backend.app.infrastructure.security.certificates import load_or_create_ca from backend.app.infrastructure.persistence.connection import close_database, database_path, initialize from backend.app.api import views from backend.app.api.session import load_identity from backend.app.api.routes import auth, implants, registry def load_key(state_dir, name, size=32): path = state_dir / name if path.is_file(): key = path.read_bytes() if len(key) != size: raise RuntimeError(f"Invalid state key: {name}") return key key = get_random_bytes(size) with path.open("xb") as handle: os.chmod(path, 0o600) handle.write(key) return key def create_app(database_path_override=None): db_path = Path(database_path_override or database_path()) initialize(db_path) state_dir = db_path.parent / "state" state_dir.mkdir(mode=0o700, parents=True, exist_ok=True) with closing(sqlite3.connect(db_path)) as connection: has_implants = connection.execute("SELECT EXISTS(SELECT 1 FROM implants)").fetchone()[0] required = ("master.key", "ca.key.pem", "ca.cert.pem") if has_implants and any(not (state_dir / name).is_file() for name in required): raise RuntimeError("Existing implants require the original master key and CA files; restore the state directory") if (state_dir / "ca.key.pem").is_file() != (state_dir / "ca.cert.pem").is_file(): raise RuntimeError("Both CA key and certificate must be present") master_key = load_key(state_dir, "master.key") ca_key, ca = load_or_create_ca(state_dir, utc_now()) app = Flask(__name__, static_folder=None) app.config.update( DATABASE=str(db_path), MAX_CONTENT_LENGTH=65_536, ) app.extensions["ledger"] = SimpleNamespace( ca_key=ca_key, ca=ca, master_key=master_key, obsigil_key=load_key(state_dir, "obsigil.key", 64), dummy_hash=generate_password_hash(get_random_bytes(32).hex(), method="scrypt"), challenge_lifetime=LIFETIME, static_root=Path(__file__).resolve().parents[3] / "frontend", ) app.before_request(load_identity) for blueprint in (auth.bp, implants.bp, registry.bp, views.bp): app.register_blueprint(blueprint) app.teardown_appcontext(close_database) @app.errorhandler(LedgerError) def service_error(error): return {"error": str(error)}, error.status @app.errorhandler(HTTPException) def http_error(error): response = error.get_response() response.set_data(app.json.dumps({"error": error.description})) response.mimetype = "application/json" return response @app.after_request def protect_private_responses(response): if response.is_json: response.headers["Cache-Control"] = "no-store" return response return app