#!/usr/bin/env python3
"""concealer — local secret manager (thin wrapper over SOPS+age).

Crypto via sops+age. This file: typed secrets (api_key/database/website/custom),
scopes (tenant/project/environment/repo) + tags + metadata (url/notes), full CRUD,
HMAC-chained audit log, professional web UI (SPA) and MCP stdio server.

Store (single encrypted JSON, kept as sops YAML):
  {"secrets":[ {"id","name","type","tenant","project","environment","repo",
                "tags":[],"url","notes","fields":{...},"created","updated"} ]}
Audit: keys/audit.log (JSONL, HMAC-chained, tamper-evident). Keeps only key
NAMES and actions, never secret VALUES.
"""
import os, sys, json, subprocess, secrets as _secrets, http.server, urllib.parse, urllib.request, html, getpass, time, webbrowser
import hashlib, hmac, shlex, re, contextlib, csv, io, tempfile, base64, shutil, fnmatch, gc, zlib, socket
from datetime import datetime, timezone, timedelta

if sys.platform.startswith("win"):
    # Windows: a redirected stdout/stderr (pipe, file, CI) defaults to the ANSI code
    # page (cp1252), so printing "→" or box-drawing glyphs raises UnicodeEncodeError.
    # Force UTF-8 so CLI/MCP output is byte-safe everywhere. No effect on Unix.
    for _s in (sys.stdout, sys.stderr):
        try: _s.reconfigure(encoding="utf-8")
        except Exception: pass

VERSION = "1.2.1"   # tracks the public mobile-app release; semver from here on
BASE = os.path.dirname(os.path.realpath(__file__))
def _default_home():
    # Repo checkout: vault lives next to the script → keep BASE (don't break existing installs).
    # Brew/package install (BASE read-only) or clean install → per-user ~/.concealer.
    if os.path.exists(os.path.join(BASE, "keys")) or os.path.exists(os.path.join(BASE, "secrets.enc.yaml")):
        return BASE
    return os.path.expanduser("~/.concealer")
HOME = os.environ.get("CONCEALER_HOME", _default_home())
FILE = os.environ.get("CONCEALER_FILE", os.path.join(HOME, "secrets.enc.yaml"))
KEY  = os.environ.get("CONCEALER_KEY",  os.path.join(HOME, "keys", "age-key.txt"))
BACKUP   = os.path.join(HOME, "keys", "age-key.txt.age")
PUBKEY   = os.path.join(HOME, "keys", "pubkey.txt")
MASTER   = os.path.join(HOME, "keys", "master.json")
AUDITKEY = os.path.join(HOME, "keys", "audit.key")
AUDITLOG = os.path.join(HOME, "keys", "audit.log")
AUDITHEAD= os.path.join(HOME, "keys", "audit.head")   # last-line anchor (tail-truncation detection)
RECOVERY = os.path.join(HOME, "keys", "recovery.json")# recovery code hashes + code-wrapped age key
AGENTS   = os.path.join(HOME, "keys", "agents.json")  # unlock token hashes + token-wrapped age key
CONFIG   = os.path.join(HOME, "keys", "config.json")
RATESTATE= os.path.join(HOME, "keys", "ratestate.json")  # per-agent disclosure window (not the value, just name+ts)
BACKUPCFG= os.path.join(HOME, "keys", "backup.json")     # auto-backup config + age-recipient-wrapped backup password (NO plaintext password)
SERVERINFO=os.path.join(HOME, "keys", "serverinfo.json") # stable per-vault identity for device discovery (id+label; NO secret)
SOPSCFG  = os.path.join(HOME, ".sops.yaml")
WEBUI    = os.path.join(BASE, "webui.html")
def _read_webui():
    """webui.html bytes, or None. Falls back to the current PATH install's copy when BASE's
    was removed by an in-place upgrade (a running server's versioned dir gets gc'd) — self-heals
    the 'not found' blank page for a server that outlived its own files."""
    cands = [WEBUI]
    for name in ("concealer", "cer"):
        p = shutil.which(name)
        if p: cands.append(os.path.join(os.path.dirname(os.path.realpath(p)), "webui.html"))
    for p in cands:
        try:
            with open(p, "rb") as f: return f.read()
        except OSError: continue
    return None
DIMS = ["tenant", "project", "environment", "repo"]
FLAGS = {"--tenant": "tenant", "--project": "project", "--env": "environment",
         "--repo": "repo", "--name": "name", "--type": "type"}

# ---- runtime config (keys/config.json; contains no secret) ----
# limits: MCP disclosure quota. per_call = max rows returned in one call;
# window_quota = max DISTINCT secrets disclosable within window_sec (blocks bulk exfiltration);
# window_quota=0 => that agent is fully blocked. agents[label] for per-agent override.
_DEFAULT_LIMITS = {"per_call": 10, "window_quota": 25, "window_sec": 3600}
_DEFAULT_CFG = {"idle": 300, "confirm_ops": ["export", "delete", "settings"],
                "limits": {"default": dict(_DEFAULT_LIMITS), "agents": {}},
                "policies": [],   # user-defined reminder policies (see policy_eval)
                # audit_anchor: push the head hash to an OFF-MACHINE append-only target (full re-forge detection)
                "audit_anchor": {"file": "", "webhook": "", "syslog": False}}
def load_cfg():
    cfg = dict(_DEFAULT_CFG)
    if os.path.exists(CONFIG):
        try: cfg.update(json.load(open(CONFIG)))
        except Exception: pass
    if os.environ.get("CONCEALER_IDLE"): cfg["idle"] = int(os.environ["CONCEALER_IDLE"])  # env override
    return cfg
def save_cfg(cfg):
    os.makedirs(os.path.dirname(CONFIG), exist_ok=True)
    with open(CONFIG, "w") as f: json.dump(cfg, f)
    os.chmod(CONFIG, 0o600)
CFG = load_cfg()

def server_info():
    """Stable per-vault identity for device discovery: {id, label}. `id` is minted once and persists, so it
    identifies THIS vault across hostname/ip/port changes and lets multiple vaults on one LAN stay distinct.
    Contains NO secret — safe to expose over /api/serverinfo and advertise via mDNS."""
    try:
        info = json.load(open(SERVERINFO))
        if info.get("id"): return info
    except Exception: pass
    info = {"id": _secrets.token_hex(8), "label": socket.gethostname().split(".")[0]}
    try:
        os.makedirs(os.path.dirname(SERVERINFO), exist_ok=True)
        with open(SERVERINFO, "w") as f: json.dump(info, f)
        os.chmod(SERVERINFO, 0o600)
    except OSError: pass
    return info
def _cfg_persist():   # called from settings POSTs: persist idle/confirm_ops/limits/policies/hibp
    save_cfg({k: CFG[k] for k in ("idle", "confirm_ops", "limits", "policies", "hibp_key", "audit_anchor",
                                  "sync_accept_remote_deletes") if k in CFG})

def _clean_limit(v):
    """Clamp/sanitize the limit dict coming from the web (per_call>=1, quota>=0 ⇒ 0=block)."""
    out = {}
    for k, lo, hi in (("per_call", 1, 1000), ("window_quota", 0, 100000), ("window_sec", 60, 604800)):
        if k in v:
            try: out[k] = max(lo, min(hi, int(v[k])))
            except (TypeError, ValueError): pass
    return out

def agent_limits(label):
    lm = CFG.get("limits") or {}
    base = dict(_DEFAULT_LIMITS); base.update(lm.get("default") or {})
    base.update((lm.get("agents") or {}).get(label) or {})
    return base

def _load_rate():
    try: return json.load(open(RATESTATE))
    except Exception: return {}
def _save_rate(s):
    try:
        with open(RATESTATE, "w") as f: json.dump(s, f)
        os.chmod(RATESTATE, 0o600)
    except OSError: pass

def rate_gate(label, rows, atomic=False):
    """Disclosure quota. Returns (allowed_rows, note).
    per_call: single-call cap; window_quota: DISTINCT name cap in the rolling window.
    Already-disclosed names are 'free' (re-querying doesn't disclose more).
    atomic=True (run_with_secrets/inject): all-or-nothing — to avoid partial env injection
    (a silently broken command + partial leak). Since the inject value never returns to the model,
    the per_call row cap is not applied; the protection = how many DISTINCT secrets are opened to the child command in the window."""
    lim = agent_limits(label); now = time.time()
    st = _load_rate()
    log = [p for p in st.get(label, []) if now - p[0] < lim["window_sec"]]   # prune old entries
    disclosed = {n for _, n in log}
    if atomic:
        remaining = max(0, lim["window_quota"] - len(disclosed))
        new_names = {e["name"] for e in rows if not (e["name"] in disclosed and lim["window_quota"] > 0)}
        if lim["window_quota"] == 0 or len(new_names) > remaining:   # quota 0 = full block
            return [], ("\n[limit] injection blocked — %d new secret(s) exceed agent '%s' window quota "
                        "(distinct %d, %d left). Narrow the scope (project/repo/env) or raise the limit in Settings."
                        % (len(new_names), label, lim["window_quota"], remaining))
        for e in rows:
            nm = e["name"]
            if not (nm in disclosed and lim["window_quota"] > 0): log.append([now, nm]); disclosed.add(nm)
        st[label] = log; _save_rate(st)
        return rows, ""
    capped = rows[:lim["per_call"]]
    remaining = max(0, lim["window_quota"] - len(disclosed))
    allowed, newn, held = [], 0, 0
    for e in capped:
        nm = e["name"]
        if nm in disclosed and lim["window_quota"] > 0: allowed.append(e)   # already disclosed → free (quota 0=full block)
        elif newn < remaining:
            allowed.append(e); log.append([now, nm]); disclosed.add(nm); newn += 1
        else: held += 1                                             # quota exhausted → hide
    st[label] = log; _save_rate(st)
    hidden = held + max(0, len(rows) - len(capped))
    note = ""
    if hidden:
        note = ("\n[limit] %d secret(s) hidden — agent '%s' (per-call <=%d, window distinct quota %d, %d left). "
                "Narrow the query (project/tag/type) or wait for the window to reset."
                % (hidden, label, lim["per_call"], lim["window_quota"], max(0, remaining - newn)))
    return allowed, note

# ---- secret types: field templates (secret fields are masked) ----
TYPES = {
    # --- developer / infra ---
    "api_key":  [("value", "secret")],
    "access_token": [("token", "secret"), ("refresh_token", "secret"), ("expires", "plain"), ("scopes", "plain")],
    "oauth":    [("client_id", "plain"), ("client_secret", "secret"), ("auth_url", "plain"), ("token_url", "plain"), ("scopes", "plain")],
    "jwt":      [("token", "secret"), ("issuer", "plain"), ("audience", "plain"), ("expires", "plain")],
    "ssh_key":  [("private_key", "secret"), ("public_key", "plain"), ("passphrase", "secret"), ("host", "plain"), ("user", "plain")],
    "certificate": [("certificate", "plain"), ("private_key", "secret"), ("chain", "plain"), ("expires", "plain")],
    "database": [("host", "plain"), ("port", "plain"), ("database", "plain"),
                 ("schema", "plain"), ("username", "plain"), ("password", "secret"),
                 ("auth_type", "plain"), ("jdbc_url", "secret")],   # connection string carries credentials → secret
    "server":   [("host", "plain"), ("port", "plain"), ("username", "plain"), ("password", "secret"), ("ssh_key", "secret")],
    "website":  [("web_url", "plain"), ("username", "plain"), ("password", "secret")],
    "login":    [("web_url", "plain"), ("username", "plain"), ("password", "secret"), ("totp", "secret")],
    # --- everyday / end-user (PII-bearing card/passport/id types INTENTIONALLY omitted) ---
    "pin":         [("pin", "secret"), ("label", "plain")],   # phone pin, door pin…
    "wifi":        [("ssid", "plain"), ("password", "secret"), ("security", "plain")],
    "membership":  [("provider", "plain"), ("member_id", "plain"), ("password", "secret")],
    "secure_note": [("note", "secret")],
    "custom":   [],   # free-form fields
}
_SECRETY = re.compile(r"pass|secret|token|value|key|credential|apikey", re.I)
_URL_CREDS = re.compile(r"://[^\s/@]*:[^\s/@]+@")   # embedded [user]:pass@ (incl. redis://:pw@; excl. host:port/)
def field_is_secret(typ, fname):
    for f, k in TYPES.get(typ, []):
        if f == fname: return k == "secret"
    return bool(_SECRETY.search(fname))
def rec_field_secret(e, fname):
    """Record-aware secrecy: per-record override → type template/name → credential embedded in the value."""
    fm = (e.get("field_meta") or {}).get(fname) or {}
    if isinstance(fm, dict) and "secret" in fm: return bool(fm["secret"])
    if field_is_secret(e.get("type", "custom"), fname): return True
    return bool(_URL_CREDS.search(str(e.get("fields", {}).get(fname, ""))))
def rec_mask(e, fname, v):
    """Masking style: field_meta.mask == 'full' → all stars; otherwise partial (mask())."""
    fm = (e.get("field_meta") or {}).get(fname) or {}
    if isinstance(fm, dict) and fm.get("mask") == "full": return "•" * 8
    return mask(v)

_KEY_CACHE = None   # decrypted age private key (process-lifetime in-memory cache; not written to disk)
def _env():
    e = dict(os.environ)
    k = _unlock_key()               # key text (hardened) or None (legacy: plaintext file)
    if k: e["SOPS_AGE_KEY"] = k     # give sops the key from memory instead of a FILE → no plaintext key on disk
    else: e["SOPS_AGE_KEY_FILE"] = KEY
    return e
def now_iso(): return datetime.now(timezone.utc).isoformat(timespec="seconds")
def mask(v):
    v = str(v); return v[:4] + "…" + v[-2:] if len(v) > 8 else ("•" * len(v) or "—")

# ---------------- error text scrubbing ----------------
# concealer delegates encryption to external tools, but no user-facing surface (CLI, TUI, web, MCP,
# extension) names them. Subprocess stderr does, so scrub every error string on its way to the user.
# Internal identifiers (file paths, env vars, argv) are untouched — only what gets printed.
_SCRUB_MAP = [(r"(?:keys[/\\\\])?age-key\.txt\.age", "the encrypted vault key"),
              (r"(?:keys[/\\\\])?age-key\.txt", "the vault key file"),
              (r"\.sops\.yaml", "the vault crypto config"),
              (r"SOPS_AGE_KEY(?:_FILE)?", "the vault key variable"),
              (r"\bage-keygen\b", "the key generator"),
              (r"\bsops\b", "the encryption engine"),
              (r"\bage\b", "the encryption engine")]
# one capturing group per entry (longest patterns first) → m.lastindex picks the replacement
_SCRUB = re.compile("(?i)" + "|".join("(%s)" % p for p, _ in _SCRUB_MAP))
def scrub(x):
    """Replace crypto-tool names/paths in an error string with neutral wording."""
    return _SCRUB.sub(lambda m: _SCRUB_MAP[m.lastindex - 1][1], str(x))

# ---------------- store ----------------
def load():
    r = subprocess.run(["sops", "-d", "--output-type", "json", FILE],
                       env=_env(), capture_output=True, text=True)
    if r.returncode: sys.exit(f"decrypt error: {scrub(r.stderr.strip())}")
    d = json.loads(r.stdout); d.setdefault("secrets", [])
    for e in d["secrets"]: norm(e)
    return d

def save(d):
    cmd = ["sops", "--encrypt", "--input-type", "json", "--output-type", "yaml",
           "--filename-override", FILE]
    if os.path.exists(SOPSCFG): cmd[1:1] = ["--config", SOPSCFG]
    payload = json.dumps(d)
    if sys.platform.startswith("win"):
        # Windows has no /dev/stdin, so sops must read a real file. Write it inside the
        # ACL-locked keys/ dir (inherits user-only access), then delete right after.
        # Documented caveat (docs/WINDOWS.md): the vault plaintext briefly touches an
        # ACL-restricted temp file here, unlike the /dev/stdin (no-disk) path on Unix.
        import concealer_win
        fd, tmp = tempfile.mkstemp(dir=os.path.dirname(KEY), suffix=".json")
        try:
            os.write(fd, payload.encode()); os.close(fd); concealer_win.secure_file(tmp)
            r = subprocess.run(cmd + [tmp], env=_env(), capture_output=True, text=True)
        finally:
            try: os.remove(tmp)
            except OSError: pass
    else:
        r = subprocess.run(cmd + ["/dev/stdin"], input=payload, env=_env(), capture_output=True, text=True)
    if r.returncode: sys.exit(f"encrypt error: {scrub(r.stderr.strip())}")
    with open(FILE, "w") as f: f.write(r.stdout)

def norm(e):
    """Upgrade old/incomplete records to the new schema (id, type, fields...)."""
    for dim in DIMS: e.setdefault(dim, "")
    e.setdefault("tags", []); e.setdefault("url", ""); e.setdefault("notes", "")
    e.setdefault("type", "api_key")
    if "fields" not in e:
        e["fields"] = {"value": e.pop("value")} if "value" in e else {}
    if not e.get("id"):
        e["id"] = hashlib.sha1((e.get("name", "") + "".join(e.get(x, "") for x in DIMS)
                                + now_iso()).encode()).hexdigest()[:12]
    e.setdefault("field_meta", {})   # {fname: {"secret":bool,"mask":"partial"|"full"}} — record-specific secrecy
    e.setdefault("collection", "")   # free-form grouping path ("a/b" nested); independent of scope — see feature-plan
    e.setdefault("rotation", {})     # {"every_days":int,"last":iso,"mode":"generate"|"manual"} — empty = no policy
    e.setdefault("env_alias", "")    # optional identifier base for env injection ("" = derive from name)
    e.setdefault("created", now_iso()); e.setdefault("updated", e["created"])
    e.setdefault("deleted", "")      # tombstone timestamp ("" = live); kept for cross-device deletion sync
    return e

def secs(d): return d["secrets"]
def live(d): return [e for e in secs(d) if not e.get("deleted")]   # non-tombstone records (user-facing views)
def by_id(d, sid): return next((e for e in secs(d) if e["id"] == sid), None)   # includes tombstones — sync needs them
def tombstone(d, e):
    """Soft-delete: keep id + name + scope + updated so the deletion can sync, but drop all secret values."""
    e["fields"] = {}; e["field_meta"] = {}; e["deleted"] = now_iso(); e["updated"] = e["deleted"]
def matches(e, sel): return all(str(e.get(k, "")) in v.split(",") for k, v in sel.items())  # v = single or comma-separated multi-select
def label(e): return "/".join(e.get(k, "") or "*" for k in DIMS)

def filt(d, sel=None, tag=None, term=None, typ=None, coll=None):
    out = []
    for e in secs(d):
        if e.get("deleted"): continue   # tombstones never appear in user-facing lists/search/get
        if sel and not matches(e, sel): continue
        if tag and not any(tg in e["tags"] for tg in tag.split(",")): continue   # multi tag: match if any one matches
        if typ and e["type"] not in typ.split(","): continue
        if coll is not None:   # collection filter: exact or sub-path ("a" -> "a", "a/b"). "" -> collection-less
            c = e.get("collection", "")
            if coll == "":
                if c: continue
            elif not (c == coll or c.startswith(coll + "/")): continue
        if term:
            hay = json.dumps({k: e.get(k) for k in DIMS + ["name", "tags", "url", "notes", "type", "collection"]}).lower()
            hay += " " + " ".join(e["fields"].keys()).lower()
            if term.lower() not in hay: continue
        out.append(e)
    return sorted(out, key=lambda e: [e.get(k, "") for k in DIMS + ["name"]])

def entry_public(e, reveal=False):
    fields = {}
    for fn, fv in e["fields"].items():
        if _bad_field_name(fn): continue   # don't expose fields with secret-like (leaked) names to the UI/MCP
        sec = rec_field_secret(e, fn)   # record-aware: override + jdbc/dsn credential heuristic
        fields[fn] = {"secret": sec, "value": fv} if (reveal or not sec) else {"secret": True, "mask": rec_mask(e, fn, fv)}
    pub = {k: e.get(k) for k in ["id", "name", "type"] + DIMS + ["tags", "url", "notes", "created", "updated"]}
    pub["fields"] = fields; pub["field_meta"] = e.get("field_meta") or {}
    pub["collection"] = e.get("collection", ""); pub["rotation"] = e.get("rotation") or {}
    pub["overdue"] = rotation_overdue(e); return pub

def rotation_overdue(e):
    """Is rotation overdue → number of days past due (>=0) or None (no policy)."""
    r = e.get("rotation") or {}
    days = r.get("every_days")
    if not days: return None
    base = r.get("last") or e.get("updated") or e.get("created")
    try: last = datetime.fromisoformat(base)
    except Exception: return None
    if last.tzinfo is None: last = last.replace(tzinfo=timezone.utc)
    over = (datetime.now(timezone.utc) - last).days - int(days)
    return over if over >= 0 else None

# ---------------- audit (HMAC chain) ----------------
def _audit_key():
    if not os.path.exists(AUDITKEY):
        with open(AUDITKEY, "w") as f: f.write(_secrets.token_hex(32))
        os.chmod(AUDITKEY, 0o600)
    return bytes.fromhex(open(AUDITKEY).read().strip())

def _last_hash():
    if not os.path.exists(AUDITLOG): return "genesis"
    last = "genesis"
    with open(AUDITLOG) as f:
        for line in f:
            line = line.strip()
            if line:
                try: last = json.loads(line)["hash"]
                except Exception: pass
    return last

def _last_seq():
    # monotonic seq no: missing (old) lines keep the order, a deleted tail is caught via the anchor
    if not os.path.exists(AUDITLOG): return 0
    last = 0
    with open(AUDITLOG) as f:
        for line in f:
            line = line.strip()
            if line:
                try: last = json.loads(line).get("seq", last)
                except Exception: pass
    return last

def _write_anchor(seq, h):
    with open(AUDITHEAD, "w") as f: json.dump({"seq": seq, "hash": h}, f)
    os.chmod(AUDITHEAD, 0o600)
def _read_anchor():
    try: return json.load(open(AUDITHEAD))
    except Exception: return None

def anchor_push(file=None, webhook=None, syslog=None, persist=False):
    """Push the current audit head (seq+hash) to OFF-MACHINE append-only targets.
    The local audit.head can be rewritten by root; an external copy (remote syslog / a file on
    another machine / webhook) makes a FULL re-forge of the chain detectable. No value/secret leaks —
    only seq + chain hash go out. Intended to be called periodically from cron."""
    anc = _read_anchor()
    if not anc: return None, []   # no audit yet
    cfg = CFG.get("audit_anchor") or {}
    file = cfg.get("file") if file is None else file
    webhook = cfg.get("webhook") if webhook is None else webhook
    syslog = cfg.get("syslog") if syslog is None else syslog
    if persist:
        CFG["audit_anchor"] = {"file": file or "", "webhook": webhook or "", "syslog": bool(syslog)}
        _cfg_persist()
    rec = {"ts": now_iso(), "seq": anc["seq"], "hash": anc["hash"]}
    line = json.dumps(rec); sent = []
    if file:
        try:
            with open(os.path.expanduser(file), "a") as f: f.write(line + "\n")
            sent.append("file")
        except OSError as ex: sys.stderr.write(f"anchor file error: {ex}\n")
    if syslog:
        try: subprocess.run(["logger", "-t", "concealer-audit", line], check=False); sent.append("syslog")
        except OSError as ex: sys.stderr.write(f"anchor syslog error: {ex}\n")
    if webhook:
        try:
            req = urllib.request.Request(webhook, data=line.encode(), headers={"Content-Type": "application/json"})
            urllib.request.urlopen(req, timeout=5); sent.append("webhook")
        except Exception as ex: sys.stderr.write(f"anchor webhook error: {ex}\n")
    audit("audit_anchor", key=f"seq={rec['seq']}", source="cli", detail=",".join(sent))
    return rec, sent

def audit(action, key="", source="cli", detail="", actor=None):
    # actor: the actor performing the action (agent name etc). Comes from CONCEALER_ACTOR env.
    if actor is None: actor = os.environ.get("CONCEALER_ACTOR", "")
    entry = {"ts": now_iso(), "seq": _last_seq() + 1, "action": action, "key": key, "source": source, "detail": detail}
    if actor: entry["actor"] = actor   # new field; if empty stays identical to old lines
    prev = _last_hash()
    h = hmac.new(_audit_key(), (prev + json.dumps(entry, sort_keys=True)).encode(), hashlib.sha256).hexdigest()
    with open(AUDITLOG, "a") as f: f.write(json.dumps({**entry, "prev": prev, "hash": h}) + "\n")
    _write_anchor(entry["seq"], h)   # anchor: catches the last line being deleted (truncation)

def audit_rows():
    rows = []
    if os.path.exists(AUDITLOG):
        with open(AUDITLOG) as f:
            for i, line in enumerate(f):
                line = line.strip()
                if line:
                    r = json.loads(line); r["n"] = i + 1; rows.append(r)
    return rows

def audit_verify():
    # ponytail: audit.key is on disk so an FS-root attacker can rewrite the chain from scratch; this verify
    # catches insert/delete/reorder and TAIL-TRUNCATION (anchor). For full immutability the
    # audit.key/anchor must be off-machine (upgrade path). See same threat model as write_master.
    prev = "genesis"; bad = None; n = 0; last_seq = 0; reason = None
    for i, rec in enumerate(audit_rows()):
        n += 1
        # hash payload = all fields except prev/hash/n → new fields (actor/seq) are backward-compatible
        entry = {k: v for k, v in rec.items() if k not in ("prev", "hash", "n")}
        h = hmac.new(_audit_key(), (prev + json.dumps(entry, sort_keys=True)).encode(), hashlib.sha256).hexdigest()
        if h != rec["hash"] or rec["prev"] != prev: bad = i + 1; reason = "chain"; break
        s = rec.get("seq")
        if s is not None:
            if last_seq and s != last_seq + 1: bad = i + 1; reason = "seq"; break  # skipped/repeated seq no
            last_seq = s
        prev = rec["hash"]
    res = {"ok": bad is None, "count": n, "broken_at": bad}
    if reason: res["reason"] = reason
    anc = _read_anchor()   # anchor: if the last hash/seq mismatches, the tail was deleted
    if bad is None and anc and (anc.get("hash") != prev or (last_seq and anc.get("seq") != last_seq)):
        res.update(ok=False, reason="truncated", broken_at=n + 1)
    # external anchor: the last head in the off-machine file must match the chain's hash at that seq.
    # even if local audit.key/head are rewritten by root, this copy catches a full re-forge.
    ext = (CFG.get("audit_anchor") or {}).get("file")
    if res.get("ok") and ext and os.path.exists(os.path.expanduser(ext)):
        try:
            last_ext = None
            with open(os.path.expanduser(ext)) as f:
                for ln in f:
                    ln = ln.strip()
                    if ln: last_ext = json.loads(ln)
            if last_ext:
                seqmap = {r.get("seq"): r["hash"] for r in audit_rows() if r.get("seq") is not None}
                es = last_ext.get("seq")
                if es not in seqmap or seqmap[es] != last_ext.get("hash"):
                    res.update(ok=False, reason="external_anchor", broken_at=es)
        except Exception: pass   # file unreadable/corrupt → don't block local verification
    return res

_ACCESS_ACTS = {"reveal", "copy", "get", "inject", "create", "update", "rotate", "set_secret"}
def last_access():
    """name -> {ts, source, action, actor}: last access derived from the audit log."""
    acc = {}
    for r in audit_rows():
        if r.get("action") in _ACCESS_ACTS:
            for k in str(r.get("key", "")).split(","):
                k = k.strip()
                if k: acc[k] = {"ts": r["ts"], "source": r.get("source", ""),
                                "action": r["action"], "actor": r.get("actor", "")}
    return acc

def access_stats():
    """name -> {count, last}: usage count + last access derived from the audit log (value-access actions only)."""
    st = {}
    _USE_ACTS = _ACCESS_ACTS - {"create"}   # 'create' is not a use (creation) — drop from the count
    for r in audit_rows():
        if r.get("action") in _USE_ACTS:
            for k in str(r.get("key", "")).split(","):
                k = k.strip()
                if not k: continue
                s = st.setdefault(k, {"count": 0, "last": None})
                s["count"] += 1; s["last"] = r["ts"]   # audit_rows is chronological → last wins
    return st

_EXP_FIELDS = ("expires", "expiry", "expires_at", "expiration", "valid_until", "not_after")
def expiry_days(e, now=None):
    """Days left from an expires-like field (negative = expired) or None (no field/unparseable).
    ponytail: ISO date/datetime + unix epoch(s/ms) heuristic; exotic formats return None."""
    now = now or datetime.now(timezone.utc)
    for fn in _EXP_FIELDS:
        v = e["fields"].get(fn)
        if not v: continue
        v = str(v).strip(); dt = None
        try:
            if re.fullmatch(r"\d{10,13}", v):
                ts = int(v); ts = ts / 1000 if ts > 1e11 else ts
                dt = datetime.fromtimestamp(ts, timezone.utc)
            else:
                dt = datetime.fromisoformat(v.replace("Z", "+00:00"))
        except Exception:
            try: dt = datetime.strptime(v[:10], "%Y-%m-%d").replace(tzinfo=timezone.utc)
            except Exception: dt = None
        if dt:
            if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc)
            return (dt - now).days
    return None

def health_scan(d=None):
    """Risk metrics per record: rotation lag, expiry, usage, reuse (no value leaks)."""
    d = d or load()
    use = access_stats(); now = datetime.now(timezone.utc)
    leak_by_name = {}
    for g in leak_scan(d):
        for u in g["uses"]:
            prev = leak_by_name.get(u["name"])
            if not prev or g["score"] > prev["score"]:
                leak_by_name[u["name"]] = {"score": g["score"], "severity": g["severity"]}
    out = []
    for e in secs(d):
        name = e["name"]; u = use.get(name, {}); lk = leak_by_name.get(name, {})
        rot = e.get("rotation") or {}
        out.append({"id": e["id"], "name": name, "type": e["type"], "scope": label(e),
                    "project": e.get("project", ""), "repo": e.get("repo", ""),
                    "environment": e.get("environment", ""), "tags": e.get("tags", []),
                    "overdue": rotation_overdue(e), "has_policy": bool(rot.get("every_days")),
                    "expires_in": expiry_days(e, now),
                    "uses": u.get("count", 0), "last_used": u.get("last"),
                    "leak_score": lk.get("score"), "leak_sev": lk.get("severity")})
    return out

# ---------------- policies (reminder rules) ----------------
# A policy: {id,name,kind,audience,enabled,notify,match{...},params{...}}. No value leaks — it only
# looks at records' META (rotation/expiry/name/tag) and leak_scan (reuse, value masked).
_POLICY_KINDS = ("rotation", "expiry", "reuse", "naming", "tagging")
_POLICY_AUD = ("all", "user", "agent", "cli", "web", "tui", "mcp")
def _policy_match(e, m):
    """Does the record fall under this policy's target filter (empty field = no restriction)."""
    m = m or {}
    for k in ("project", "environment", "repo", "type", "collection"):
        want = (m.get(k) or "").strip()
        if want and str(e.get(k, "")) != want: return False
    tag = (m.get("tag") or "").strip()
    if tag and tag not in (e.get("tags") or []): return False
    return True
def _as_int(v, dflt=0):
    try: return int(v)
    except (TypeError, ValueError): return dflt
def _policy_violation(p, e, now, reuse_names):
    """Human-readable reason (str) if the record violates the policy, else None."""
    k = p.get("kind"); pr = p.get("params") or {}
    if k == "rotation":
        maxd = _as_int(pr.get("max_days")); rot = e.get("rotation") or {}; ev = rot.get("every_days")
        over = rotation_overdue(e)
        if not ev: return "no rotation policy"
        if maxd and ev > maxd: return f"rotates every {ev}d (> {maxd}d)"
        if over is not None: return f"{over}d overdue"
        return None
    if k == "expiry":
        warn = _as_int(pr.get("warn_days"), 30); ed = expiry_days(e, now)
        if ed is None: return "no expiry set" if pr.get("require") else None
        if ed < 0: return f"expired {-ed}d ago"
        if ed <= warn: return f"expires in {ed}d"
        return None
    if k == "reuse":
        return "value reused across records" if e["name"] in reuse_names else None
    if k == "naming":
        rx = pr.get("regex") or ""
        if not rx: return None
        try: return None if re.search(rx, e["name"]) else f"name must match /{rx}/"
        except re.error: return None
    if k == "tagging":
        req = [t for t in (pr.get("tags") or []) if t]
        miss = [t for t in req if t not in (e.get("tags") or [])]
        return "missing tag(s): " + ", ".join(miss) if miss else None
    return None
def policy_eval(d=None):
    """Violating records per policy. reuse is computed only when needed (leak_scan is expensive)."""
    d = d or load(); pols = CFG.get("policies") or []
    reuse_names = set()
    if any(p.get("kind") == "reuse" and p.get("enabled", True) for p in pols):
        for g in leak_scan(d):
            for u in g["uses"]: reuse_names.add(u["name"])
    now = datetime.now(timezone.utc); out = []
    for p in pols:
        viols = []
        if p.get("enabled", True):
            for e in secs(d):
                if not _policy_match(e, p.get("match")): continue
                r = _policy_violation(p, e, now, reuse_names)
                if r: viols.append({"id": e["id"], "name": e["name"], "scope": label(e), "reason": r})
        out.append({**p, "violations": viols, "count": len(viols)})
    return out
def _policy_clean(pol):
    """Normalize the policy dict coming from web/CLI to the schema (generate/preserve id)."""
    pid = (pol.get("id") or "").strip() or hashlib.sha1((pol.get("name", "") + now_iso()).encode()).hexdigest()[:12]
    match = pol.get("match") or {}
    params = pol.get("params") if isinstance(pol.get("params"), dict) else {}
    return {"id": pid, "name": (pol.get("name") or "policy").strip()[:60],
            "kind": pol.get("kind") if pol.get("kind") in _POLICY_KINDS else "rotation",
            "audience": pol.get("audience") if pol.get("audience") in _POLICY_AUD else "all",
            "enabled": bool(pol.get("enabled", True)), "notify": bool(pol.get("notify", False)),
            "match": {k: str(match.get(k, "") or "").strip() for k in ("project", "environment", "repo", "type", "collection", "tag")},
            "params": params}
def policy_upsert(pol):
    pol = _policy_clean(pol); pols = CFG.get("policies") or []
    for i, x in enumerate(pols):
        if x.get("id") == pol["id"]: pols[i] = pol; break
    else: pols.append(pol)
    CFG["policies"] = pols; _cfg_persist(); return pol
def policy_delete(pid):
    pols = CFG.get("policies") or []; n = len(pols)
    CFG["policies"] = [x for x in pols if x.get("id") != pid]; _cfg_persist()
    return n != len(CFG["policies"])

# ---------------- leak / reuse scan ----------------
def leak_scan(d=None):
    """Find records sharing the same secret VALUE and risk-score them. No value leaks (masked)."""
    d = d or load(); by_val = {}
    for e in secs(d):
        for fn, fv in e["fields"].items():
            if not fv or not rec_field_secret(e, fn): continue   # override + embedded-credential values included too
            by_val.setdefault(str(fv), []).append(
                {"id": e["id"], "name": e["name"], "field": fn, "scope": label(e),
                 "project": e.get("project", ""), "environment": e.get("environment", "")})
    groups = []
    for val, uses in by_val.items():
        if len(uses) < 2: continue
        projects = sorted({u["project"] for u in uses if u["project"]})
        envs = sorted({u["environment"] for u in uses if u["environment"]})
        names = {u["name"] for u in uses}
        # score: use count + project/env spread + distinct name + prod sharing
        score = min(100, len(uses) * 12 + max(0, len(projects) - 1) * 20 +
                    max(0, len(envs) - 1) * 15 + (10 if len(names) > 1 else 0) +
                    (15 if any(x.lower() == "prod" for x in envs) else 0))
        sev = "high" if score >= 70 else "med" if score >= 40 else "low"
        groups.append({"count": len(uses), "projects": projects, "envs": envs,
                       "score": score, "severity": sev, "mask": mask(val), "uses": uses})
    groups.sort(key=lambda g: -g["score"])
    return groups

# ---------------- folder scan / import ----------------
_TOKEN_PATTERNS = [
    ("aws_access_key", re.compile(r"AKIA[0-9A-Z]{16}")),
    ("openai",         re.compile(r"sk-[A-Za-z0-9_-]{20,}")),
    ("github_pat",     re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}")),
    ("slack",          re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}")),
    ("google_api",     re.compile(r"AIza[0-9A-Za-z_-]{35}")),
    ("jwt",            re.compile(r"eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}")),
]
_ENV_LINE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+?)\s*$")
_SKIP_DIRS = {".git", "node_modules", "venv", ".venv", "__pycache__", "dist", "build", ".next", ".terraform"}
def _unquote(v):
    v = v.strip()
    if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'": v = v[1:-1]
    return v
def _looks_secret(name, val):
    if len(val) < 6 or val.startswith("$"): return False
    if _SECRETY.search(name): return True
    if any(rx.search(val) for _, rx in _TOKEN_PATTERNS): return True
    # high entropy + length (random token)
    return (len(val) >= 20 and len(set(val)) >= 12
            and bool(re.search(r"[0-9]", val)) and bool(re.search(r"[A-Za-z]", val)))

# ---- custom-field NAME validation: a field name should be a short identifier, not a secret VALUE ----
_FIELD_NAME_OK = re.compile(r"^[A-Za-z0-9 _.\-]{1,40}$")   # >40 chars or non-identifier chars like / + : = @ = leaked
def _bad_field_name(name):
    """True => this 'field name' looks like a credential/key/token/URL (a leaked value entered by mistake)."""
    n = (name or "").strip()
    if not n: return True
    if not _FIELD_NAME_OK.match(n): return True                        # long name or URL/base64/non-identifier char
    if any(rx.search(n) for _, rx in _TOKEN_PATTERNS): return True     # AKIA…/sk-…/ghp_…/AIza…/JWT pattern embedded in the name
    return any(len(r) >= 20 and re.search(r"\d", r) and re.search(r"[A-Za-z]", r)
               for r in re.split(r"[ _.\-]+", n))                      # 20+ mixed alphanumerics with no separator = random token
def _clean_fields(fields):
    """(clean_fields, dropped_names) — drops fields whose name is secret-like (a leak)."""
    fields = fields or {}
    bad = [k for k in fields if _bad_field_name(k)]
    return ({k: v for k, v in fields.items() if k not in bad}, bad)
# ---- environment variable / global variable scan (macOS + Linux; Windows later) ----
# live process env + shell profile files (login/interactive) — export/set KEY=VALUE
_ENV_PROFILES = ("~/.bashrc", "~/.bash_profile", "~/.profile", "~/.zshrc", "~/.zshenv",
                 "~/.zprofile", "~/.kshrc", "~/.config/fish/config.fish",
                 "/etc/environment", "/etc/profile")
_ENV_SKIP = {"SOPS_AGE_KEY", "SOPS_AGE_KEY_FILE", "CONCEALER_TOKEN", "PATH", "PWD", "OLDPWD",
             "LS_COLORS", "MANPATH", "INFOPATH", "TERMCAP"}
# terminal/editor/session noise — drop from the scan if the name isn't really a secret (see _SECRETY)
_ENV_NAME_NOISE = re.compile(r"SESSION|ASKPASS|DEBUGPY|ENDPOINTS|TERM_FEATURES|_SOCK$|_PID$|_PATH$|COLORTERM", re.I)
_FISH_SET = re.compile(r"^\s*set\s+(?:-[gxUl]+\s+)*([A-Za-z_][A-Za-z0-9_]*)\s+(.+?)\s*$")
def env_scan():
    """Return secret-like candidates from the local machine's ENV/GLOBAL variables:
    live os.environ + shell profile files (export/set KEY=VALUE). No value goes out (mask).
    macOS + Linux. ponytail: Windows system/user env (registry) later."""
    cands = {}
    def add(name, val, src):
        val = _unquote(str(val))
        if name in _ENV_SKIP or not val or re.search(r"\s", val): return   # has a space = path/sentence, not a token
        if not _SECRETY.search(name):   # if the name doesn't say secret: drop path/session-noise values
            if val.startswith(("/", "~", "./", "../", "http://", "https://")): return
            if _ENV_NAME_NOISE.search(name): return
        if _looks_secret(name, val):
            cands.setdefault((name, val), {"name": name, "value": val, "mask": mask(val), "source": src})
    for k, v in os.environ.items(): add(k, v, "env")
    for pf in _ENV_PROFILES:
        p = os.path.expanduser(pf)
        if not os.path.isfile(p): continue
        try: txt = open(p, errors="ignore").read()
        except Exception: continue
        for line in txt.splitlines():
            if line.lstrip().startswith("#"): continue
            m = _ENV_LINE.match(line)
            if m: add(m.group(1), m.group(2), os.path.basename(p))
            else:
                mf = _FISH_SET.match(line)
                if mf: add(mf.group(1), mf.group(2), os.path.basename(p))
    return sorted(cands.values(), key=lambda c: c["name"])

def scan_folder(root, history=False, env=False):
    """Return secret-like KEY=VALUE pairs as candidates from the folder's .env/.tfvars/.envrc
    + (optional) shell history + (optional) environment variables. No value goes out (listed masked)."""
    root = os.path.expanduser(root or ""); cands = {}
    def add(name, val, src):
        val = _unquote(val)
        if _looks_secret(name, val):
            cands.setdefault((name, val), {"name": name, "value": val, "mask": mask(val), "source": src})
    if os.path.isdir(root):
        for dp, dns, fns in os.walk(root):
            dns[:] = [x for x in dns if x not in _SKIP_DIRS]
            for fn in fns:
                if not (fn.startswith(".env") or fn.endswith(".env") or fn == ".envrc" or fn.endswith(".tfvars")): continue
                fp = os.path.join(dp, fn)
                try: txt = open(fp, errors="ignore").read()
                except Exception: continue
                for line in txt.splitlines():
                    if line.lstrip().startswith("#"): continue
                    m = _ENV_LINE.match(line)
                    if m: add(m.group(1), m.group(2), os.path.relpath(fp, root))
    if history:
        for hf in ("~/.zsh_history", "~/.bash_history"):
            hp = os.path.expanduser(hf)
            if not os.path.exists(hp): continue
            try: txt = open(hp, errors="ignore").read()
            except Exception: continue
            for m in re.finditer(r"(?:export\s+)?([A-Z][A-Z0-9_]{2,})=([^\s;|&'\"]+)", txt):
                add(m.group(1), m.group(2), os.path.basename(hp))
    if env:
        for c in env_scan(): cands.setdefault((c["name"], c["value"]), c)
    return sorted(cands.values(), key=lambda c: c["name"])

# ---------------- shell history leak scan ----------------
_HIST_FILES = ("~/.zsh_history", "~/.bash_history", "~/.histfile", "~/.sh_history", "~/.ksh_history")
# narrow secret-name for CLI KEY=VALUE (unlike the broad _SECRETY: `value|key|id` alone isn't enough)
_HIST_SECRET_NAME = re.compile(r"secret|token|passw|credential|api[_-]?key|access[_-]?key|private[_-]?key|bearer|\bpat\b", re.I)
def _high_entropy(v):
    """Does it look like a real credential/token: long + mixed. Short/dictionary-like project codes, hosts,
    path fragments etc. are DROPPED — they match as substrings everywhere in history and produce false positives."""
    return (len(v) >= 12 and len(set(v)) >= 8
            and bool(re.search(r"[0-9]", v)) and bool(re.search(r"[A-Za-z]", v)))
def _vault_vals(d):
    """HIGH-ENTROPY secret field values in the vault. Empty set if the vault is locked/absent.
    Only genuinely secret-like values; short labels (project code, tenant) are not scanned (see _high_entropy)."""
    vals = set()
    try:
        for e in secs(d if d is not None else load()):
            for fn, fv in e["fields"].items():
                if fv and rec_field_secret(e, fn) and _high_entropy(str(fv)): vals.add(str(fv))
    except SystemExit: pass
    return vals
def _hist_hits(line, vault_vals):
    """Secret fragments in line: (value, reason, severity). No value goes out; the caller masks."""
    hits = []
    for v in vault_vals:
        # match at a full-token boundary (no alphanumeric neighbor) — avoids matching part of a longer token
        if v in line and re.search(r"(?<![A-Za-z0-9])" + re.escape(v) + r"(?![A-Za-z0-9])", line):
            hits.append((v, "vault", "high"))
    for kind, rx in _TOKEN_PATTERNS:
        for m in rx.finditer(line): hits.append((m.group(0), kind, "high"))
    # KEY=VALUE inline: on the command line far noisier than in a .env file (`--file=`, `--tag-value=` etc.).
    # So a STRICT rule here: the name must really look like a secret-name (NOT the broad `value|key|id`) AND
    # the value must be high-entropy. Otherwise file-path/URL/tag values produce false positives.
    for m in re.finditer(r"(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=([^\s;|&'\"]+)", line):
        name, val = m.group(1), _unquote(m.group(2))
        if _HIST_SECRET_NAME.search(name) and _high_entropy(val): hits.append((val, "env:" + name, "med"))
    return hits
def history_scan(d=None):
    """Find credential/secret values in shell history files (vault-match + token pattern).
    No value goes out; the command line is returned masked."""
    vault_vals = _vault_vals(d)
    out = []
    for hf in _HIST_FILES:
        hp = os.path.expanduser(hf)
        if not os.path.exists(hp): continue
        try: lines = open(hp, errors="ignore").read().splitlines()
        except Exception: continue
        for i, line in enumerate(lines):
            hits = _hist_hits(line, vault_vals)
            if not hits: continue
            red = line
            for v in sorted({h[0] for h in hits}, key=len, reverse=True): red = red.replace(v, mask(v))
            red = re.sub(r"^:\s*\d+:\d+;", "", red)   # zsh EXTENDED_HISTORY meta (: <ts>:<dur>;) — no need to show
            out.append({"file": os.path.basename(hp), "path": hp, "line": i + 1,
                        "mask": mask(hits[0][0]), "cmd": red[:240],
                        "reasons": sorted({h[1] for h in hits}),
                        "severity": "high" if any(h[2] == "high" for h in hits) else "med"})
    out.sort(key=lambda x: (x["severity"] != "high", x["file"], x["line"]))
    return out
def history_purge(targets, d=None):
    """targets: [{path, line}] — delete the given lines from history (first a *.concealer.bak backup).
    Safety: skips if the line no longer contains a secret (prevents deleting the wrong line). Returns count deleted.
    ponytail: the line-no index assumes append-only history; concurrent reordering is rare, and the backup undoes it."""
    vault_vals = _vault_vals(d)
    by_file = {}
    for t in targets: by_file.setdefault(os.path.expanduser(t["path"]), set()).add(int(t["line"]))
    removed = 0
    for hp, lns in by_file.items():
        if not os.path.exists(hp): continue
        lines = open(hp, errors="ignore").read().splitlines(keepends=True)
        kept, drop = [], 0
        for i, ln in enumerate(lines):
            if (i + 1) in lns and _hist_hits(ln, vault_vals): drop += 1; continue
            kept.append(ln)
        if drop:
            shutil.copy2(hp, hp + ".concealer.bak")
            with open(hp, "w") as f: f.writelines(kept)
            removed += drop
    return removed

# ================= online leak / exposure =================
# SECURITY: the FULL secret value is NEVER sent over the network. HIBP Pwned Passwords k-anonymity is used:
# only the first 5 hex of the value's SHA-1 are queried; matching happens locally. (see pwned_count)
_PWNED_UA = "concealer-secret-manager"
def pwned_count(value, timeout=8):
    """HIBP Pwned Passwords k-anonymity check. ONLY the SHA-1 prefix (5 hex) is sent; the API returns the
    thousands of suffixes sharing that prefix, and the full-hash comparison is done LOCALLY. The full value/hash never GOES OUT to the network.
    Returns: occurrence count (>=0) or -1 (network error). ponytail: a single provider (HIBP range) — this is the privacy-safe one."""
    h = hashlib.sha1(value.encode("utf-8", "ignore")).hexdigest().upper()
    prefix, suffix = h[:5], h[5:]
    try:
        req = urllib.request.Request("https://api.pwnedpasswords.com/range/" + prefix,
                                     headers={"User-Agent": _PWNED_UA, "Add-Padding": "true"})
        body = urllib.request.urlopen(req, timeout=timeout).read().decode("utf-8", "ignore")
    except Exception: return -1
    for line in body.splitlines():
        sfx, _, cnt = line.partition(":")
        if sfx.strip().upper() == suffix:
            try: return int(cnt.strip().split()[0])
            except (ValueError, IndexError): return 0
    return 0

# CWE references (static; source: cwe.mitre.org) — attached to findings
_CWE = {
    "798": ("CWE-798", "Use of Hard-coded Credentials", "https://cwe.mitre.org/data/definitions/798.html"),
    "259": ("CWE-259", "Use of Hard-coded Password", "https://cwe.mitre.org/data/definitions/259.html"),
    "321": ("CWE-321", "Use of Hard-coded Cryptographic Key", "https://cwe.mitre.org/data/definitions/321.html"),
    "312": ("CWE-312", "Cleartext Storage of Sensitive Information", "https://cwe.mitre.org/data/definitions/312.html"),
    "532": ("CWE-532", "Insertion of Sensitive Information into Log File", "https://cwe.mitre.org/data/definitions/532.html"),
    "540": ("CWE-540", "Inclusion of Sensitive Information in Source Code", "https://cwe.mitre.org/data/definitions/540.html"),
}
def _cwe(ids): return [{"id": _CWE[i][0], "title": _CWE[i][1], "url": _CWE[i][2]} for i in ids if i in _CWE]
# keyhacks-like validation hint: per token type a "is it live / how to check" GUIDE (SENDS no value)
_VALIDATE = [
    (re.compile(r"AKIA[0-9A-Z]{16}"), "AWS key — verify locally: `aws sts get-caller-identity`. keyhacks.md#aws-access-key-id"),
    (re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}"), "GitHub token — scopes via `curl -H 'Authorization: token <T>' https://api.github.com/user` (run locally). keyhacks.md#github"),
    (re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}"), "Slack token — test auth.test locally. keyhacks.md#slack-api-token"),
    (re.compile(r"AIza[0-9A-Za-z_-]{35}"), "Google API key — restrict & rotate in Cloud Console. keyhacks.md#google-api-key"),
    (re.compile(r"sk-[A-Za-z0-9_-]{20,}"), "OpenAI/Stripe-style key — rotate at the provider; never paste it into an online checker."),
]
def _validate_hint(value):
    for rx, msg in _VALIDATE:
        if rx.search(value): return msg
    return ""
def exposure_scan(names=None, ids=None, sel=None, online=True, d=None):
    """Run the SECRET field values of the selected secrets through an online leak check (HIBP k-anonymity).
    If ids are given, only those RECORDS (id — exact; does NOT mix up same-named records in different scopes/collections);
    names/sel for backward compatibility. The same value is queried once.
    SECURITY: the full value never GOES OUT to the network (only the SHA-1 prefix). online=False → only static CWE/hints, no network."""
    d = d or load(); out = []; seen = {}
    idset = set(ids) if ids is not None else None
    for e in secs(d):
        if idset is not None and e["id"] not in idset: continue
        if names is not None and e["name"] not in names: continue
        if sel and not matches(e, sel): continue
        for fn, fv in e["fields"].items():
            fv = str(fv or "")
            # the vault's OWN secret values — no false-positive worry; weak passwords must be checked too
            # (HIBP is strongest on weak passwords). The _high_entropy filter is NOT applied here; only trivial short values are dropped.
            if len(fv) < 6 or not rec_field_secret(e, fn): continue
            cnt = None
            if online:
                if fv in seen: cnt = seen[fv]
                else: cnt = pwned_count(fv); seen[fv] = cnt
            ids = ["798"]
            if e.get("type") in ("ssh_key", "certificate"): ids.append("321")
            elif "pass" in fn.lower(): ids.append("259")
            out.append({"id": e["id"], "name": e["name"], "field": fn, "scope": label(e), "mask": mask(fv),
                        "pwned": cnt, "severity": "high" if (cnt and cnt > 0) else ("med" if cnt == -1 else "low"),
                        "cwe": _cwe(ids), "validate": _validate_hint(fv)})
    out.sort(key=lambda x: -((x["pwned"] or 0)))
    return out

def _hibp_key(): return (CFG.get("hibp_key") or os.environ.get("CONCEALER_HIBP_KEY") or "").strip()
def hibp_breaches(email, timeout=8):
    """HIBP account leak: breaches an email appears in. Requires a v3 API key (user-supplied; CFG/env).
    Only the email the user entered is sent. Returns {ok, breaches|error, manual?}."""
    email = (email or "").strip()
    if not email or "@" not in email: return {"ok": False, "error": "bad_email"}
    key = _hibp_key()
    manual = "https://haveibeenpwned.com/account/" + urllib.parse.quote(email)
    if not key: return {"ok": False, "error": "no_key", "manual": manual}
    url = "https://haveibeenpwned.com/api/v3/breachedaccount/" + urllib.parse.quote(email) + "?truncateResponse=false"
    try:
        req = urllib.request.Request(url, headers={"hibp-api-key": key, "User-Agent": _PWNED_UA})
        rows = json.loads(urllib.request.urlopen(req, timeout=timeout).read().decode("utf-8", "ignore"))
    except Exception as ex:
        code = getattr(ex, "code", None)
        if code == 404: return {"ok": True, "breaches": []}       # clean — no leak
        return {"ok": False, "error": ("http_%s" % code) if code else "net", "manual": manual}
    return {"ok": True, "breaches": [{"name": b.get("Name"), "title": b.get("Title"), "date": b.get("BreachDate"),
             "count": b.get("PwnCount"), "data": b.get("DataClasses", [])} for b in rows]}

# ---------------- git history / log / gitignore scan (LOCAL — no value leaves the network) ----------------
def _git(repo, *args, timeout=30):
    try:
        r = subprocess.run(["git", "-C", repo, *args], capture_output=True, text=True, timeout=timeout, errors="ignore")
        return r.stdout if r.returncode == 0 else ""
    except Exception: return ""
def _is_git(repo): return bool(_git(repo, "rev-parse", "--is-inside-work-tree").strip())
_TOKEN_RX_ALL = re.compile("|".join(rx.pattern for _, rx in _TOKEN_PATTERNS))
_SECRET_FILE_RX = re.compile(
    r"(^|/)(\.env(\.[\w.-]+)?|\.envrc|[^/]*\.pem|[^/]*\.key|[^/]*\.p12|[^/]*\.pfx|id_rsa|id_ed25519|"
    r"[^/]*\.tfvars|credentials(\.json)?|\.npmrc|\.pypirc|secrets?\.(ya?ml|json))$", re.I)
_LOG_FILE_RX = re.compile(r"\.log(\.[\w.-]+)?$", re.I)
def gitignore_gaps(repo):
    """Suggest files that may carry secrets (.env/*.pem/id_rsa/...) if git isn't ignoring them.
    .gitignore (git check-ignore) + .claudeignore (fnmatch) are evaluated together."""
    repo = os.path.expanduser(repo or ""); cand = []
    for dp, dns, fns in os.walk(repo):
        dns[:] = [x for x in dns if x not in _SKIP_DIRS and x != ".git"]
        for fn in fns:
            rel = os.path.relpath(os.path.join(dp, fn), repo).replace(os.sep, "/")
            if _SECRET_FILE_RX.search(rel): cand.append(rel)
        if len(cand) > 500: break
    extra = []
    for ig in (".claudeignore", ".cursorignore", ".aiignore"):
        p = os.path.join(repo, ig)
        if os.path.isfile(p):
            extra += [l.strip() for l in open(p, errors="ignore") if l.strip() and not l.startswith("#")]
    gaps = []
    for rel in sorted(set(cand))[:100]:
        if _is_git(repo) and _git(repo, "check-ignore", rel).strip(): continue
        if any(fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch(os.path.basename(rel), pat) for pat in extra): continue
        gaps.append(rel)
    return gaps
def git_scan(repo, d=None):
    """Search for secrets in the repo git history + working tree (LOCAL). Returns:
      committed: whether vault secret values were ever committed (git log -S pickaxe — exact, value not sent)
      tracked:   token pattern in files tracked at HEAD (git grep)
      gitignore_gaps: un-ignored secret files"""
    repo = os.path.expanduser(repo or "")
    if not _is_git(repo): return {"git": False}
    vals = _vault_vals(d); committed = []
    for v in list(vals)[:200]:   # ponytail: pickaxe per value is expensive; 200 cap (multi-thread to extend)
        if v.startswith("-"): continue
        out = _git(repo, "log", "--all", "--oneline", "-S", v, timeout=20)
        commits = [ln.split(" ", 1) for ln in out.splitlines() if ln.strip()][:10]
        if commits:
            committed.append({"mask": mask(v), "commits": [
                {"hash": c[0], "subject": (c[1] if len(c) > 1 else "")[:80]} for c in commits]})
    tracked = []
    for ln in _git(repo, "grep", "-nIE", _TOKEN_RX_ALL.pattern, timeout=20).splitlines()[:200]:
        m = re.match(r"([^:]+):(\d+):(.*)", ln)
        if not m: continue
        hit = _TOKEN_RX_ALL.search(m.group(3))
        tracked.append({"file": m.group(1), "line": int(m.group(2)), "mask": mask(hit.group(0)) if hit else ""})
    return {"git": True, "committed": committed, "tracked": tracked, "gitignore_gaps": gitignore_gaps(repo)}
def log_scan(root, d=None):
    """Search *.log files in the directory/repo (and under logs/) for vault secrets + token patterns. Masked."""
    root = os.path.expanduser(root or ""); vault_vals = _vault_vals(d); out = []
    if not os.path.isdir(root): return out
    for dp, dns, fns in os.walk(root):
        dns[:] = [x for x in dns if x not in _SKIP_DIRS and x != ".git"]
        in_logdir = os.path.basename(dp).lower() in ("logs", "log")
        for fn in fns:
            if not (_LOG_FILE_RX.search(fn) or (in_logdir and not fn.startswith("."))): continue
            fp = os.path.join(dp, fn)
            try:
                if os.path.getsize(fp) > 20 * 1024 * 1024: continue     # 20MB cap
                for i, line in enumerate(open(fp, errors="ignore")):
                    hits = _hist_hits(line, vault_vals)
                    if not hits: continue
                    red = line
                    for v in sorted({h[0] for h in hits}, key=len, reverse=True): red = red.replace(v, mask(v))
                    out.append({"file": os.path.relpath(fp, root), "line": i + 1, "mask": mask(hits[0][0]),
                                "cmd": red.strip()[:240], "reasons": sorted({h[1] for h in hits}),
                                "severity": "high" if any(h[2] == "high" for h in hits) else "med"})
                    if len(out) >= 500: return out
            except Exception: continue
    return out
def git_remediation(repo, files=None, names=None):
    """GUIDE to purging secrets from git history (command doc tailored to repo/file/names).
    SECURITY: concealer NEVER runs these commands; it only produces the text — the user applies it."""
    rname = os.path.basename(os.path.abspath(os.path.expanduser(repo or ""))) or "your-repo"
    files = [f for f in (files or []) if f][:30]; names = [n for n in (names or []) if n][:50]
    fl = files or ["path/to/secret-file"]
    q = lambda s: shlex.quote(s)
    md = [f"# Remediation — purge committed secrets from `{rname}`", "",
          "> ⚠️ concealer never rewrites git history for you. Read each command, then run it yourself.", "",
          "## 1. Rotate first (do this before anything else)", "",
          "A secret is compromised the instant it is pushed — rewriting history does **not** un-leak it. "
          "Rotate/revoke the affected credential at its provider now."]
    if names: md += ["", "Affected secrets:"] + [f"- `{n}`" for n in names]
    md += ["", "## 2. Stop tracking + ignore", "", "```sh"] + \
          [f"git rm --cached {q(f)}" for f in fl] + \
          ["printf '%s\\n' " + " ".join(q(f) for f in fl) + " >> .gitignore",
           "git commit -m 'stop tracking secrets; add to .gitignore'", "```",
           "", "## 3. Purge from history — git filter-repo (recommended)", "",
           "```sh", "# pip install git-filter-repo"] + \
          [f"git filter-repo --path {q(f)} --invert-paths" for f in fl] + \
          ["```", "", "## 4. Alternative — BFG Repo-Cleaner", "", "```sh",
           "# https://rtyley.github.io/bfg-repo-cleaner/",
           f"bfg --delete-files {os.path.basename(fl[0])}",
           "git reflog expire --expire=now --all && git gc --prune=now --aggressive", "```",
           "", "## 5. Force-push + coordinate", "", "```sh", "git push --force --all",
           "git push --force --tags", "```",
           "Teammates must re-clone (old clones still hold the secret). Ask GitHub/GitLab support to expire cached views.",
           "", "## 6. Prevent recurrence", "",
           "Add pre-commit scanning: **gitleaks**, **TruffleHog**, or **detect-secrets**. "
           "Validate whether a leaked key is still live with **keyhacks** (locally, never via an online paster).", ""]
    return "\n".join(md)

def _native_pickdir():
    """Local app: open the OS folder-picker dialog (Finder/Explorer), return the chosen path (cancel=None)."""
    try:
        if sys.platform == "darwin":
            scr = 'try\nPOSIX path of (choose folder with prompt "concealer")\nend try'
            r = subprocess.run(["osascript", "-e", scr], capture_output=True, text=True, timeout=300)
            return (r.stdout.strip() or None)
        if sys.platform.startswith("linux"):
            if shutil.which("zenity"):
                r = subprocess.run(["zenity", "--file-selection", "--directory"], capture_output=True, text=True, timeout=300)
                return (r.stdout.strip() or None)
            if shutil.which("kdialog"):
                r = subprocess.run(["kdialog", "--getexistingdirectory", os.path.expanduser("~")], capture_output=True, text=True, timeout=300)
                return (r.stdout.strip() or None)
            return None
        if sys.platform.startswith("win"):
            ps = ('Add-Type -AssemblyName System.Windows.Forms;'
                  '$d=New-Object System.Windows.Forms.FolderBrowserDialog;'
                  'if($d.ShowDialog() -eq "OK"){[Console]::Out.Write($d.SelectedPath)}')
            r = subprocess.run(["powershell", "-NoProfile", "-Command", ps], capture_output=True, text=True, timeout=300)
            return (r.stdout.strip() or None)
    except Exception:
        return None
    return None
def _import_cands(d, cands, scope):
    n_new = n_skip = 0
    for c in cands:
        ident = dict(scope); ident["name"] = c["name"]
        hit = next((e for e in live(d) if matches(e, ident)), None)   # a tombstone match would swallow the import
        if hit and str(hit["fields"].get("value")) == c["value"]: n_skip += 1; continue
        if hit:
            hit["fields"]["value"] = c["value"]; hit["updated"] = now_iso(); n_new += 1
        else:
            origin = "scan-history" if c["source"] in (".zsh_history", ".bash_history") else "scan-folder"
            e = dict(ident); e["type"] = "api_key"; e["fields"] = {"value": c["value"]}
            e["tags"] = ["scan", origin]; e["url"] = ""; e["notes"] = f"scan: {c['source']}"
            secs(d).append(norm(e)); n_new += 1
    return n_new, n_skip

# ---------------- portable export / import (encrypted with age -p) ----------------
def merge_secrets(d, incoming, mode="overwrite"):
    """Merge incoming records into the vault. Conflict (same id, else name+scope) resolution via `mode`:
    overwrite=update the existing one (default), skip=leave existing untouched, duplicate=always add as a new record."""
    n_new = n_upd = n_skip = 0
    for i, raw in enumerate(incoming):
        e = norm(dict(raw)); cur = None
        if mode != "duplicate":   # duplicate: skip match lookup, always add new
            cur = by_id(d, e["id"])
            if not cur:   # a different machine may produce a different id → also try by name+scope
                ident = {dim: e.get(dim, "") for dim in DIMS}; ident["name"] = e["name"]
                cur = next((x for x in secs(d) if matches(x, ident)), None)
        if cur:
            if mode == "skip": n_skip += 1; continue
            for k in ["name", "type"] + DIMS + ["tags", "url", "notes", "fields"]: cur[k] = e[k]
            cur["updated"] = now_iso(); n_upd += 1
        else:
            if by_id(d, e["id"]):   # in duplicate mode id may collide → generate a fresh id
                e["id"] = hashlib.sha1((e["name"] + label(e) + now_iso() + str(i)).encode()).hexdigest()[:12]
            secs(d).append(e); n_new += 1
    return n_new, n_upd, n_skip

def _encrypt_bundle(pw, secrets_list):
    """age -p encrypt a {"secrets": [...]} JSON blob; returns portable age bytes. Values never touch the wire in plaintext."""
    plain = json.dumps({"secrets": secrets_list, "exported": now_iso()}).encode()
    # ponytail: age wants a file argument → plaintext briefly in temp (0600), removed in finally
    tin = tempfile.NamedTemporaryFile(delete=False); tout = tin.name + ".age"
    try:
        tin.write(plain); tin.close(); os.chmod(tin.name, 0o600)
        rc, err = _age_pw(["-p", "-o", tout, tin.name], pw, confirm=True)
        if rc: raise RuntimeError(scrub(err.strip()) or "encryption error")
        return open(tout, "rb").read()
    finally:
        for p in (tin.name, tout):
            try: os.remove(p)
            except OSError: pass

def _decrypt_bundle(pw, blob):
    """De-obfuscate + age -p decrypt a bundle; returns the parsed dict ({"secrets": [...]})."""
    blob = _cer_unwrap(blob)                # de-obfuscate .cerbak; raw age bundles pass through
    tin = tempfile.NamedTemporaryFile(delete=False, suffix=".age"); tout = tin.name + ".json"
    try:
        tin.write(blob); tin.close()
        rc, err = _age_pw(["-d", "-o", tout, tin.name], pw)
        if rc: raise RuntimeError("wrong password or corrupt bundle")
        return json.loads(open(tout, errors="ignore").read())
    finally:
        for p in (tin.name, tout):
            try: os.remove(p)
            except OSError: pass

def export_bundle(pw):
    """Portable human backup: live records only (tombstones are sync-only), encrypted with the master password via 'age -p'."""
    return _encrypt_bundle(pw, live(load()))

def import_bundle(pw, blob, mode="overwrite"):
    """Decrypt an 'age -p'-encrypted bundle and merge into the vault. pw = the bundle's (source machine) password.
    mode: conflict resolution (overwrite|skip|duplicate) → passed to merge_secrets."""
    data = _decrypt_bundle(pw, blob)
    with _vault_lock(): d = load(); nn, nu, ns = merge_secrets(d, data.get("secrets", []), mode); save(d)
    return nn, nu, ns

_MERGE_KEYS = ["name", "type"] + DIMS + ["tags", "url", "notes", "fields", "field_meta",
                                       "collection", "rotation", "env_alias", "created", "updated", "deleted"]
def _rec_hash(e):
    return hashlib.sha256(json.dumps({k: e.get(k) for k in _MERGE_KEYS}, sort_keys=True, default=str).encode()).hexdigest()

def sync_merge(d, incoming):
    """Bidirectional last-write-wins device sync. Match by id (fallback name+scope); adopt whichever record has the
    newer `updated` timestamp, tombstones included (a deletion is just a record whose newer version is deleted).
    now_iso() strings are fixed-width UTC → lexicographic compare == chronological. Equal timestamps → the higher
    content hash wins, so both sides deterministically pick the same version. Returns count applied.
    ponytail: tombstones are kept forever (no purge) — a personal vault's deletions are few; add TTL purge if it grows."""
    applied = 0
    for raw in incoming:
        e = norm(dict(raw)); cur = by_id(d, e["id"])
        if not cur:   # a different device may have minted a different id for the same logical secret
            ident = {dim: e.get(dim, "") for dim in DIMS}; ident["name"] = e["name"]
            cur = next((x for x in secs(d) if matches(x, ident)), None)
        if cur:
            if e["updated"] > cur["updated"] or (e["updated"] == cur["updated"] and _rec_hash(e) > _rec_hash(cur)):
                for k in _MERGE_KEYS:
                    if k in e: cur[k] = e[k]
                applied += 1
        else:
            secs(d).append(e); applied += 1
    return applied

def sync_bundle(pw, blob):
    """Device sync: decrypt the peer's bundle (incl. tombstones), LWW-merge into the vault, save, and return a fresh
    bundle of the FULL merged set (incl. tombstones) so the peer can converge to the same state. Returns (applied, out_blob)."""
    data = _decrypt_bundle(pw, blob)
    inc = [r for r in data.get("secrets", []) if _rec_ok(r)]   # same shape/timestamp checks as the ssh path
    with _vault_lock(): d = load(); applied = sync_merge(d, inc); save(d)
    return applied, _encrypt_bundle(pw, secs(d))   # full set incl tombstones — the peer needs deletions too

# ---------------- machine pairing + ssh sync ----------------
# `pair <host>` runs ONCE with both vaults' master passwords: each vault records the other under
# d["sync_peers"] (inside the encrypted vault — never plaintext on disk). The remote mints a dedicated,
# revocable token (label "sync:<peer vault id>", source "sync") and hands it back; only the initiating vault
# keeps it. A "sync" token opens NOTHING but `sync-serve` (refused by _unlock_key and the MCP gate).
# `sync <host>` then runs unattended with a human CLI token or a sync-only local token
# (`agent register <name> --sync-only`, source "sync-local"); MCP agent tokens are refused. Records cross
# ssh stdin/stdout only as age ciphertext addressed to the receiving vault's public key. Each side drops
# malformed / future-dated records, refuses a mass deletion unless --allow-deletes, snapshots the encrypted
# vault file before saving, and merges under the vault lock. Revoke on either side drops the pairing.
# Ceiling: every unlock token wraps the vault key, so code running as the user with ANY token can still
# unwrap it by hand — these gates stop the CLI/MCP paths, not a same-user attacker writing their own crypto.
_AGE_RCPT = re.compile(r"age1[0-9a-z]{20,}")
_TS_RE = re.compile(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\+00:00")      # now_iso() shape (desktop + mobile sync.js)
_HOST_RE = re.compile(r"[A-Za-z0-9_.@:\[\]%][A-Za-z0-9_.@:\[\]%-]*")  # ssh destination; never starts with '-'
_CMD_RE = re.compile(r"[A-Za-z0-9_./=:+@-]+(?: [A-Za-z0-9_./=:+@-]+)*")   # plain words: no shell metacharacters
_PEERID_RE = re.compile(r"[0-9a-f]{8,32}")
_REMOTE_PATH = 'PATH="$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.local/bin"'   # non-login ssh PATH misses these
SYNC_MAX_SKEW = 300                                   # seconds a peer clock may run ahead
SNAPDIR = os.path.join(HOME, "keys", "snapshots")     # pre-sync copies of the ENCRYPTED vault file
PAIRFAIL = os.path.join(HOME, "keys", "pairfail.json")
_REC_STR = {"id", "name", "type", *DIMS, "url", "notes", "collection", "env_alias", "created", "updated", "deleted"}
_REC_KEYS = _REC_STR | {"tags", "fields", "field_meta", "rotation"}

def _ts_ok(s, empty=False):
    if empty and s == "": return True
    if not isinstance(s, str) or not _TS_RE.fullmatch(s): return False
    return datetime.fromisoformat(s) <= datetime.now(timezone.utc) + timedelta(seconds=SYNC_MAX_SKEW)

def _rec_ok(r):
    """Strict shape check for a record arriving from a peer: known keys, right types, sane timestamps."""
    if not isinstance(r, dict) or not set(r) <= _REC_KEYS: return False
    if not all(isinstance(r.get(k), str) and r[k] for k in ("id", "name")): return False
    if any(k in r and not isinstance(r[k], str) for k in _REC_STR): return False
    if not isinstance(r.get("tags", []), list) or not all(isinstance(t, str) for t in r.get("tags", [])): return False
    if not all(isinstance(r.get(k, {}), dict) for k in ("fields", "field_meta", "rotation")): return False
    if not all(isinstance(v, (str, int, float, bool)) or v is None for v in r.get("fields", {}).values()): return False
    return _ts_ok(r.get("updated")) and _ts_ok(r.get("created", r["updated"])) and _ts_ok(r.get("deleted", ""), empty=True)

import threading
_LOCK_TL = threading.local()   # per-thread re-entry depth (web handlers run in threads → each locks via flock)
@contextlib.contextmanager
def _vault_lock():
    """Serialize load→merge→save across processes (sync vs CLI set/rm/…). No-op where flock is missing (Windows)."""
    if getattr(_LOCK_TL, "depth", 0):   # re-entrant within a thread (e.g. `import` → import_bundle)
        _LOCK_TL.depth += 1
        try: yield
        finally: _LOCK_TL.depth -= 1
        return
    try: import fcntl
    except ImportError: fcntl = None
    if not fcntl: yield; return
    os.makedirs(os.path.join(HOME, "keys"), exist_ok=True)
    with open(os.path.join(HOME, "keys", "vault.lock"), "a") as f:
        for _ in range(240):   # ≤2 min: a human sitting on a password prompt must not hang cron forever
            try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB); break
            except BlockingIOError: time.sleep(0.5)
        else: raise RuntimeError("vault busy (another concealer process holds the lock)")
        _LOCK_TL.depth = 1
        try: yield
        finally: _LOCK_TL.depth = 0; fcntl.flock(f, fcntl.LOCK_UN)

SNAP_KEEP_DAYS = 14
def _snapshot(deleting=False):
    """Restore point before a sync save: a copy of the ENCRYPTED vault file (no plaintext; needs no backup
    password, so unattended runs can make it). Restore = copy it back over secrets.enc.yaml.
    Retention is by AGE, never by count: copies younger than 14 days stay, and a copy taken before a sync that
    deletes records ("-del") is never removed automatically."""
    os.makedirs(SNAPDIR, mode=0o700, exist_ok=True); os.chmod(SNAPDIR, 0o700)
    stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%f")
    dst = os.path.join(SNAPDIR, f"pre-sync-{stamp}{'-del' if deleting else ''}.enc.yaml")
    shutil.copy2(FILE, dst); os.chmod(dst, 0o600)
    cutoff = time.time() - SNAP_KEEP_DAYS * 86400
    for f in os.listdir(SNAPDIR):
        fp = os.path.join(SNAPDIR, f)
        if f.startswith("pre-sync-") and "-del" not in f and os.path.getmtime(fp) < cutoff: os.remove(fp)
    return dst

def _age_enc_to(rcpt, text):
    """Encrypt to an age recipient via stdin→stdout, so the plaintext never touches disk."""
    if not _AGE_RCPT.fullmatch(rcpt or ""): raise RuntimeError("bad peer public key")
    r = subprocess.run(["age", "-r", rcpt], input=text.encode(), capture_output=True)
    if r.returncode: raise RuntimeError(scrub(r.stderr.decode(errors="ignore").strip()) or "encryption error")
    return base64.b64encode(r.stdout).decode()

def _sync_open(b64):
    """Decrypt a peer bundle with our vault key → raw record list (validated later, under the lock)."""
    raw = json.loads(_age_dec_priv(base64.b64decode(b64))).get("secrets", [])
    return raw if isinstance(raw, list) else []

def _sync_merge_checked(d, raw, allow_deletes=False):
    """Drop malformed/future-dated records, LWW-merge into a COPY of d, refuse a mass deletion unless allowed.
    → (merged copy, applied, rejected, ids newly deleted)."""
    inc = [r for r in raw if _rec_ok(r)]
    work = json.loads(json.dumps(d)); before = {e["id"] for e in live(work)}
    applied = sync_merge(work, inc)
    gone = sorted(before - {e["id"] for e in live(work)})
    if not allow_deletes and len(gone) > 3 and len(gone) * 10 > len(before):
        raise RuntimeError(f"refusing to delete {len(gone)} of {len(before)} records in one sync (rerun with --allow-deletes)")
    return work, applied, len(raw) - len(inc), gone

def _sync_call(host, cmd, req, timeout=120):
    """One request/response over ssh: JSON frame on stdin, JSON line back. CONCEALER_SSH overrides the
    transport (tests). BatchMode → never hangs on a prompt under cron; '--' + host/cmd checks → no option injection."""
    if not _HOST_RE.fullmatch(host or ""): raise RuntimeError("bad ssh host")
    if not _CMD_RE.fullmatch(cmd or ""): raise RuntimeError("bad remote command")
    argv = shlex.split(os.environ.get("CONCEALER_SSH", "ssh")) + ["-T", "-o", "BatchMode=yes", "--", host,
                                                                   f"{_REMOTE_PATH} {cmd} sync-serve"]
    try: r = subprocess.run(argv, input=json.dumps(req), capture_output=True, text=True, timeout=timeout)
    except subprocess.TimeoutExpired: raise RuntimeError(f"{host}: timed out")
    lines = [ln for ln in r.stdout.splitlines() if ln.strip()]
    try: resp = json.loads(lines[-1])
    except Exception: raise RuntimeError(f"{host}: no answer ({scrub(r.stderr.strip()[-300:]) or 'rc=%d' % r.returncode})")
    if resp.get("error"): raise RuntimeError(f"{host}: {resp['error']}")
    return resp

def _find_peer(d, who):
    """Pairing entry by vault id, ssh host or label → (id, entry) or (None, None)."""
    for pid, p in d.get("sync_peers", {}).items():
        if who in (pid, p.get("host"), p.get("label")): return pid, p
    return None, None

def _pair_throttle(failed=None):
    """Remote pair attempts: sleep 2^n s (≤60) after n consecutive failures; reset on success."""
    try: n = json.load(open(PAIRFAIL)).get("n", 0)
    except Exception: n = 0
    if failed is None:
        if n: time.sleep(min(2 ** n, 60))
        return
    with open(PAIRFAIL, "w") as f: json.dump({"n": n + 1 if failed else 0, "ts": now_iso()}, f)
    os.chmod(PAIRFAIL, 0o600)

def _deny_agent(what):
    """pair/sync never run on an MCP agent token (an agent could otherwise trigger them via run_with_secrets)."""
    label, src = _mcp_agent()
    if src == "agent":
        audit(f"{what}_denied", source="cli", detail="agent token", actor=label)
        sys.exit(f"{what}: agent tokens are not allowed. Cron: concealer agent register <name> --sync-only")

def sync_serve():
    """Remote end of pair/sync (hidden command, run over ssh). Reads ONE JSON frame from stdin, writes ONE
    JSON line. Never prompts, never prints values; every error is a scrubbed {"error": ...} and audited."""
    global _KEY_CACHE
    out = lambda o: print(json.dumps(o))
    op, who = None, ""
    try:
        req = json.loads(sys.stdin.read() or "{}"); op = req.get("op"); me = server_info()
        if op == "pair":                                  # human-approved: needs THIS vault's master password
            peer = req.get("peer") or {}
            if not _AGE_RCPT.fullmatch(peer.get("pub", "")) or not _PEERID_RE.fullmatch(peer.get("id", "")):
                return out({"error": "bad pairing request"})
            who = str(peer.get("label", ""))[:64]; _pair_throttle()
            key = key_from_master(req.get("pw", ""))
            _pair_throttle(failed=not key)
            if not key: audit("pair_fail", key=who, source="sync"); return out({"error": "wrong master password"})
            _KEY_CACHE = key; tl = f"sync:{peer['id']}"
            tok = mint_token(key, tl, "sync")
            with _vault_lock():
                d = load(); d.setdefault("sync_peers", {})[peer["id"]] = {
                    "label": who, "pub": peer["pub"], "token_label": tl, "paired": now_iso()}
                save(d)
            audit("pair", key=who, source="sync", detail=f"peer={peer['id']}", actor=tl)
            return out({"ok": True, "id": me["id"], "label": me["label"], "pub": _recipient(), "token": tok})
        tok = req.get("token", ""); te = _find_token(tok)
        if not te or te.get("source") != "sync":
            audit("sync_fail", source="sync", detail="bad token"); return out({"error": "not paired (token invalid or revoked)"})
        _KEY_CACHE = resolve_token(tok); pid = req.get("from", ""); who = te["label"]
        if op == "sync": raw = _sync_open(req.get("b64", ""))   # decrypt outside the lock
        with _vault_lock():
            d = load(); p = d.get("sync_peers", {}).get(pid)
            if not p or p.get("token_label") != te["label"]:
                audit("sync_fail", source="sync", detail="unknown peer", actor=who); return out({"error": "not paired"})
            if op == "unpair":
                del d["sync_peers"][pid]; save(d); revoke_token(te["label"])
                audit("pair_revoke", key=p["label"], source="sync", detail="by peer", actor=who); return out({"ok": True})
            if op != "sync": return out({"error": "unknown op"})
            dry = bool(req.get("dry"))
            ok_del = bool(req.get("allow_deletes")) and str(CFG.get("sync_accept_remote_deletes", "")).lower() in ("1", "true", "yes", "on")
            work, applied, rej, gone = _sync_merge_checked(d, raw, ok_del)   # a peer can't waive OUR guard unless we opted in
            if applied and not dry: _snapshot(bool(gone)); save(work)
        sent = len(secs(work)); blob = _age_enc_to(p["pub"], json.dumps({"secrets": secs(work)}))
        audit("sync", key=p["label"], source="sync", actor=who,
              detail=f"recv={len(raw)} applied={applied} rejected={rej} sent={sent} deleted={','.join(gone[:50])}" + (" dry" if dry else ""))
        return out({"ok": True, "recv": len(raw), "applied": applied, "rejected": rej, "sent": sent, "b64": blob})
    except SystemExit as ex:   # load()/save() exit on crypto errors
        audit("sync_fail", source="sync", detail=f"{op}: {scrub(ex.code)}"[:200], actor=who or None); return out({"error": scrub(ex.code)})
    except Exception as ex:
        audit("sync_fail", source="sync", detail=f"{op}: {scrub(ex)}"[:200], actor=who or None); return out({"error": scrub(ex)})

def pair_cmd(a):
    """pair <host> [--remote-cmd C] | pair [--list] | pair --revoke <host|label|id>"""
    global _KEY_CACHE, _UNLOCK_FOR
    _UNLOCK_FOR = "pair"
    rev = _flag(a, "--revoke")
    if rev or not a or a[0] == "--list": _deny_agent("pair")   # token-driven ops; pairing itself needs master passwords
    if rev:
        with _vault_lock():
            d = load(); pid, p = _find_peer(d, rev)
            if not p: sys.exit(f"no pairing named '{rev}'.")
            if p.get("token"):                            # initiating side: also kill the remote token
                try: _sync_call(p["host"], p.get("cmd", "concealer"), {"op": "unpair", "from": server_info()["id"], "token": p["token"]}, 30)
                except Exception as ex:
                    if not p.get("pending_revoke"):       # keep it until the peer confirms; `sync` retries
                        p["pending_revoke"] = now_iso(); save(d)
                        audit("pair_revoke_pending", key=p["host"], source="cli", detail=scrub(ex)[:200], actor=_cli_actor())
                        return print(f"remote not reached ({scrub(ex)}): pairing disabled, revoke will retry on the next "
                                     f"'concealer sync {p['host']}' (or run --revoke again to drop it locally).")
                    print("warning: remote still not reached — dropping the pairing locally; revoke it there too.")
            if p.get("token_label"): revoke_token(p["token_label"])
            del d["sync_peers"][pid]; save(d)
        audit("pair_revoke", key=p.get("host") or p["label"], source="cli", actor=_cli_actor())
        return print(f"pairing removed: {p.get('host') or p['label']}")
    if not a or a[0] == "--list":
        peers = load().get("sync_peers", {})
        if not peers: return print("no pairings. pair with: concealer pair <ssh-host>")
        for pid, p in peers.items():
            role = ("revoke pending → " if p.get("pending_revoke") else "sync → ") + p["host"] if p.get("host") else "serves sync"
            print(f"  {p.get('label') or pid:16} {role:30} paired {p['paired']}")
        return
    host = a[0]; cmd = _flag(a, "--remote-cmd") or "concealer"
    if not _HOST_RE.fullmatch(host): sys.exit("bad ssh host.")
    if not _CMD_RE.fullmatch(cmd): sys.exit("bad --remote-cmd (plain words only, no shell characters).")
    pw = getpass.getpass("Master password (this machine): "); key = key_from_master(pw)
    if not key: sys.exit("wrong password.")
    _KEY_CACHE = key; me = server_info()
    rpw = getpass.getpass(f"Master password on {host}: ")   # travels only on ssh stdin
    if not rpw: sys.exit("the remote master password is required.")
    try: resp = _sync_call(host, cmd, {"op": "pair", "pw": rpw, "peer": {"id": me["id"], "label": me["label"], "pub": _recipient()}})
    except Exception as ex: sys.exit(f"pair error: {scrub(ex)}")
    if not _AGE_RCPT.fullmatch(resp.get("pub") or "") or not resp.get("token") or not _PEERID_RE.fullmatch(resp.get("id") or ""):
        sys.exit("pair error: bad answer from peer")
    with _vault_lock():
        d = load(); peers = d.setdefault("sync_peers", {})
        for k in [k for k, v in peers.items() if v.get("host") == host]: del peers[k]   # re-pair replaces
        peers[resp["id"]] = {"label": str(resp.get("label", ""))[:64], "host": host, "cmd": cmd, "pub": resp["pub"],
                             "token": resp["token"], "paired": now_iso()}
        save(d)
    audit("pair", key=host, source="cli", detail=f"peer={resp['id']}", actor=_cli_actor())
    print(f"paired with {host} ({resp.get('label')}). Sync now (cron-friendly): concealer sync {host}")

def sync_cmd(a):
    """sync <host|label> [--dry] [--allow-deletes] [--via HOST]: one encrypted two-way LWW round trip with a paired vault."""
    global _UNLOCK_FOR
    _UNLOCK_FOR = "sync"; _deny_agent("sync")
    dry = "--dry" in a; allow = "--allow-deletes" in a
    a = [x for x in a if x not in ("--dry", "--allow-deletes")]; via = _flag(a, "--via")
    if not a: sys.exit("usage: concealer sync <host> [--dry] [--allow-deletes] [--via HOST]")
    if via is not None and not _HOST_RE.fullmatch(via): sys.exit("bad --via host.")
    d = load(); pid, p = _find_peer(d, a[0]); actor = _cli_actor()
    if not p or not p.get("token"): sys.exit(f"not paired with '{a[0]}': run 'concealer pair {a[0]}' once.")
    host = via or p["host"]; cmd = p.get("cmd", "concealer")
    if p.get("pending_revoke"):                           # finish an earlier revoke instead of syncing
        try: _sync_call(host, cmd, {"op": "unpair", "from": server_info()["id"], "token": p["token"]}, 30)
        except Exception as ex: sys.exit(f"pairing is being revoked; remote still not reached: {scrub(ex)}")
        with _vault_lock():
            d = load(); d.get("sync_peers", {}).pop(pid, None); save(d)
        audit("pair_revoke", key=host, source="cli", detail="completed", actor=actor)
        return print(f"pairing removed: {host}")
    mine = secs(d)
    try:
        resp = _sync_call(host, cmd, {"op": "sync", "from": server_info()["id"], "token": p["token"], "dry": dry,
                                      "allow_deletes": allow, "b64": _age_enc_to(p["pub"], json.dumps({"secrets": mine}))})
        raw = _sync_open(resp["b64"])
        with _vault_lock():                              # re-read: a write during the round trip must not be clobbered
            d = load(); work, applied, rej, gone = _sync_merge_checked(d, raw, allow)
            if applied and not dry: _snapshot(bool(gone)); save(work)
    except Exception as ex:
        audit("sync_fail", key=host, source="sync", detail=scrub(ex)[:200], actor=actor); sys.exit(f"sync error: {scrub(ex)}")
    audit("sync", key=host, source="sync", actor=actor,
          detail=f"sent={len(mine)} recv={len(raw)} applied={applied} rejected={rej} remote_applied={resp.get('applied', 0)} "
                 f"deleted={','.join(gone[:50])}" + (" dry" if dry else ""))
    print(f"sync {host}{' (dry)' if dry else ''}: sent {len(mine)}, received {len(raw)}; "
          f"updated here {applied}, there {resp.get('applied', 0)}" + (f"; rejected {rej}" if rej else ""))

# ---------------- backup (.cerbak) ----------------
# .cerbak = the whole vault encrypted with age -p using the BACKUP PASSWORD (different from master, required).
# Its output is opaque binary age ciphertext → opening the file reveals nothing; restore via import.
# Auto-backup: the backup password is wrapped to the vault's age PUBLIC key (keys/backup.json); only the age
# private key (in memory while unlocked) decrypts it. The plaintext backup password is NEVER written to disk.
CER_EXT = ".cerbak"    # old backups had a ".cer" extension; the import path ignores extension, rotation recognizes both
_DEFAULT_BACKUP = {"enabled": False, "interval_h": 24, "dir": "", "keep": 7, "last": None}

# .cerbak obfuscation: XOR the age ciphertext with a keystream derived from a FIXED, PUBLIC seed so the
# raw file shows no 'age-encryption.org'/'scrypt'/'sops' markers — just opaque bytes.
# ponytail: COSMETIC only. The seed is in this source, so this provides ZERO confidentiality — it only
# hides the format from a casual `cat`/text-editor look. The REAL encryption is age with the backup
# password (unchanged). Not a "cipher" replacing age; a reversible masking layer on top. (zlib was tried
# first but stores incompressible age ciphertext verbatim, leaking the header — hence XOR.)
_CER_OBF_SEED = b"concealer-cerbak-obfuscation-v1"
def _cer_keystream(n):
    out = bytearray(); ctr = 0
    while len(out) < n:
        out += hashlib.sha256(_CER_OBF_SEED + ctr.to_bytes(8, "big")).digest(); ctr += 1
    return bytes(out[:n])
def _cer_wrap(blob):
    ks = _cer_keystream(len(blob)); return bytes(b ^ k for b, k in zip(blob, ks))
def _cer_unwrap(blob):
    """Raw age bundles (old .cer / any .age export) start with the ASCII header → pass through untouched;
    masked .cerbak files are XOR'd back to age ciphertext (XOR is its own inverse)."""
    if blob[:18] == b"age-encryption.org": return blob
    return _cer_wrap(blob)

def make_backup(pw):
    """Encrypt the whole vault with the backup password, then obfuscate → opaque .cerbak bytes (import restores it)."""
    return _cer_wrap(export_bundle(pw))

def _cer_name():
    return "concealer-" + now_iso()[:19].replace(":", "").replace("-", "") + CER_EXT   # concealer-YYYYMMDDTHHMMSS.cerbak

def _recipient():
    return open(PUBKEY).read().strip() if os.path.exists(PUBKEY) else None

def _age_enc_pub(data):
    """Encrypt data to an age recipient (public key) → ciphertext bytes. Passwordless; decrypting needs the age private key."""
    rcpt = _recipient()
    if not rcpt: raise RuntimeError("no pubkey (run init first)")
    tin = tempfile.NamedTemporaryFile(delete=False)
    tin.write(data if isinstance(data, bytes) else data.encode()); tin.close(); tout = tin.name + ".age"
    try:
        r = subprocess.run(["age", "-r", rcpt, "-o", tout, tin.name], capture_output=True, text=True)
        if r.returncode: raise RuntimeError(scrub(r.stderr.strip()) or "encryption error")
        return open(tout, "rb").read()
    finally:
        for p in (tin.name, tout):
            try: os.remove(p)
            except OSError: pass

def _age_dec_priv(blob):
    """Decrypt a recipient-encrypted blob with the age private key. Hardened vault: key is passed via stdin (-i -), never WRITTEN to disk."""
    key = _unlock_key()                       # hardened: text ; legacy: None (plaintext file KEY)
    tin = tempfile.NamedTemporaryFile(delete=False, suffix=".age"); tin.write(blob); tin.close()
    try:
        if key: r = subprocess.run(["age", "-d", "-i", "-", tin.name], input=key, capture_output=True, text=True)
        else:   r = subprocess.run(["age", "-d", "-i", KEY, tin.name], capture_output=True, text=True)
        if r.returncode: raise RuntimeError(scrub(r.stderr.strip()) or "decryption error")
        return r.stdout
    finally:
        try: os.remove(tin.name)
        except OSError: pass

def _backup_cfg():
    d = dict(_DEFAULT_BACKUP)
    if os.path.exists(BACKUPCFG):
        try: d.update(json.load(open(BACKUPCFG)))
        except Exception: pass
    return d
def _save_backup_cfg(d):
    os.makedirs(os.path.dirname(BACKUPCFG), exist_ok=True)
    with open(BACKUPCFG, "w") as f: json.dump(d, f)
    os.chmod(BACKUPCFG, 0o600)

def _rotate_backups(d, keep):
    """Delete the oldest .cer files in the folder, keep the newest `keep` (names are time-sorted)."""
    if keep <= 0: return
    p = os.path.expanduser(d)
    try: files = sorted(os.path.join(p, n) for n in os.listdir(p) if n.endswith((".cer", ".cerbak")))
    except OSError: return
    for old in files[:-keep]:
        try: os.remove(old)
        except OSError: pass

def _write_cer(pw, dst_dir, keep=7):
    blob = make_backup(pw); p = os.path.expanduser(dst_dir); os.makedirs(p, exist_ok=True)
    path = os.path.join(p, _cer_name())
    with open(path, "wb") as f: f.write(blob)
    os.chmod(path, 0o600); _rotate_backups(dst_dir, keep)
    return path

def run_auto_backup():
    """Write a .cer to the configured folder (unwraps the wrapped password with the age key). Ignores enabled/interval (manual/cron)."""
    c = _backup_cfg()
    if not c.get("dir") or not c.get("pw_wrapped"): raise RuntimeError("auto-backup not configured (folder+password)")
    pw = _age_dec_priv(base64.b64decode(c["pw_wrapped"]))
    path = _write_cer(pw, c["dir"], c.get("keep", 7))
    c["last"] = now_iso(); _save_backup_cfg(c)
    audit("backup_auto", source="auto", detail=os.path.basename(path))
    return path

def _auto_backup_maybe():
    """If auto-backup is on and the interval has elapsed, silently write a .cer (unlock/activity hook; errors swallowed)."""
    c = _backup_cfg()
    if not c.get("enabled") or not c.get("pw_wrapped") or not c.get("dir"): return
    if c.get("last"):
        try:
            if datetime.now(timezone.utc) - datetime.fromisoformat(c["last"]) < timedelta(hours=c.get("interval_h", 24)):
                return
        except Exception: pass
    try: run_auto_backup()
    except Exception: pass

# ---------------- age (expect) / master password ----------------
def _age_pw(args, passphrase, confirm=False):
    if sys.platform.startswith("win"):
        # Windows has no `expect`/`/dev/tty`; drive age through a ConPTY (pywinpty).
        # This branch is never taken on Unix — the expect path below is unchanged.
        import concealer_win
        return concealer_win.age_pw(args, passphrase, confirm)
    # NOTE: age's encrypt prompt is "Enter passphrase (leave empty ...): " → its end is NOT "passphrase:".
    # So match on the "passphrase" substring (present in both the encrypt and decrypt prompts),
    # otherwise every call times out and waits 30s.
    lines = ["set timeout 30", "set pw $env(CONCEALER_PW)",
             "spawn age " + " ".join(shlex.quote(a) for a in args),
             'expect "passphrase"', 'send -- "$pw\\r"']
    if confirm: lines += ['expect "passphrase"', 'send -- "$pw\\r"']
    lines += ["expect eof", "catch wait rc", "exit [lindex $rc 3]"]
    r = subprocess.run(["expect", "-c", "\n".join(lines)],
                       env=dict(os.environ, CONCEALER_PW=passphrase), capture_output=True, text=True)
    return r.returncode, r.stdout + r.stderr

def _ask_new_password():
    while True:
        p1 = getpass.getpass("Set master password: ")
        if not p1: print("cannot be empty."); continue
        if p1 != getpass.getpass("Repeat: "): print("did not match, try again."); continue
        return p1

_SN, _SR, _SP = 16384, 8, 1   # token/recovery KDF: inputs are already 100-144 bit, so cost factor matters little
_MASTER_N = 1 << 17           # master-PASSWORD verifier: OWASP scrypt guidance (2^17) — resists offline cracking of master.json
def _scrypt(pw, salt, n=_SN, r=_SR, p=_SP):
    # maxmem scales with the work factor (128*N*r*p bytes) + headroom, so a higher N never hits the cap.
    maxmem = 128 * n * r * p + (16 * 1024 * 1024)
    return hashlib.scrypt(pw.encode(), salt=salt, n=n, r=r, p=p, dklen=32, maxmem=maxmem)
def write_master(pw):
    salt = os.urandom(16)
    with open(MASTER, "w") as f:
        json.dump({"salt": salt.hex(), "hash": _scrypt(pw, salt, _MASTER_N).hex(), "n": _MASTER_N, "r": _SR, "p": _SP}, f)
    os.chmod(MASTER, 0o600)
def verify_master(pw):
    if os.path.exists(MASTER):
        m = json.load(open(MASTER))
        ok = hmac.compare_digest(_scrypt(pw, bytes.fromhex(m["salt"]), m["n"], m["r"], m["p"]),
                                 bytes.fromhex(m["hash"]))
        if ok and int(m.get("n", 0)) < _MASTER_N: write_master(pw)   # lazy-upgrade legacy vaults to the stronger N
        return ok
    if os.path.exists(BACKUP):
        rc, _ = _age_pw(["--decrypt", "-o", os.devnull, BACKUP], pw)
        if rc == 0: write_master(pw)
        return rc == 0
    return True

# ---------------- recovery codes ----------------
# Purpose: (a) recover the vault if the master password is forgotten, (b) stop someone who has ONLY
# obtained the master password from changing it and taking over (passwd 2nd factor).
# Code = ~100-bit; each code wraps the age key (age -p) → any one recovers. On disk only the
# scrypt hash + code-wrapped encrypted key are stored, the PLAINTEXT code is NEVER kept.
RECV_N = 8
_RC_ALPHA = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"   # low confusion (no 0/O/1/I); 256%32==0 → no bias
def _gen_codes(n=RECV_N):
    def one():
        raw = "".join(_RC_ALPHA[b % 32] for b in os.urandom(20))   # 20*5 = 100 bit
        return "-".join(raw[i:i+4] for i in range(0, 20, 4))
    return [one() for _ in range(n)]

def _age_unwrap(blob, pw):
    """Decrypt the code-wrapped key ciphertext, return the age key text."""
    tin = tempfile.NamedTemporaryFile(delete=False, suffix=".age"); tout = tin.name + ".key"
    try:
        tin.write(blob); tin.close()
        rc, err = _age_pw(["-d", "-o", tout, tin.name], pw)
        if rc: raise RuntimeError("wrong or corrupt code")
        return open(tout, "rb").read()
    finally:
        for p in (tin.name, tout):
            try: os.remove(p)
            except OSError: pass

def write_recovery(codes, keytext):
    salt = os.urandom(16)
    entries = [{"h": _scrypt(c, salt).hex(), "blob": base64.b64encode(_age_enc_bytes(keytext, c)).decode()} for c in codes]
    with open(RECOVERY, "w") as f: json.dump({"salt": salt.hex(), "codes": entries}, f)
    os.chmod(RECOVERY, 0o600)

def _recovery_data():
    return json.load(open(RECOVERY)) if os.path.exists(RECOVERY) else None
def recovery_index(code):
    d = _recovery_data()
    if not d: return None
    h = _scrypt(code.strip(), bytes.fromhex(d["salt"])).hex()
    for i, e in enumerate(d["codes"]):
        if hmac.compare_digest(e["h"], h): return i
    return None
def consume_recovery(i):
    d = _recovery_data(); d["codes"].pop(i)
    with open(RECOVERY, "w") as f: json.dump(d, f)
    os.chmod(RECOVERY, 0o600)

def _print_codes(codes):
    bar = "=" * 58
    print("\n" + bar)
    print("  RECOVERY CODES — THIS SCREEN IS SHOWN ONCE")
    print("  Save these SOMEWHERE ELSE (password manager/vault/paper).")
    print("  Not stored in PLAINTEXT on disk; if you do not copy them now they are gone.")
    print("   - if you FORGET the master password:  concealer recover")
    print("   - CHANGING the master password also needs a code (passwd)")
    print(bar)
    for i, c in enumerate(codes, 1): print(f"   {i}.  {c}")
    print(bar + "\n")

# ---------------- key-at-rest + unlock tokens ----------------
# the age private key is not kept on disk as PLAINTEXT: only the BACKUP (master-pw encrypted) and
# optional token/code-wrapped copies. Given to sops from memory via SOPS_AGE_KEY.
# Token = long-lived (agent) or TTL'd (human/cli); its VALUE lives only in the client env
# (CONCEALER_TOKEN), on disk only the scrypt hash + token-wrapped key are stored.
# Default lifetime for a human/cli token (agent tokens never expire). Shorter = smaller window
# if a shell holding the token is exposed. Override in seconds with CONCEALER_TOKEN_TTL.
TOKEN_TTL = int(os.environ.get("CONCEALER_TOKEN_TTL", 3600))   # 1h default
def _age_enc_bytes(data, pw):
    """Encrypt arbitrary bytes with pw via age -p, return ciphertext."""
    tin = tempfile.NamedTemporaryFile(delete=False)
    tin.write(data if isinstance(data, bytes) else data.encode()); tin.close()
    tout = tin.name + ".age"
    try:
        rc, err = _age_pw(["-p", "-o", tout, tin.name], pw, confirm=True)
        if rc: raise RuntimeError(scrub(err.strip()) or "encryption error")
        return open(tout, "rb").read()
    finally:
        for p in (tin.name, tout):
            try: os.remove(p)
            except OSError: pass

def key_from_master(pw):
    """Decrypt BACKUP with the master pw → age key text (None on wrong pw). Both verifies and yields the key."""
    if not os.path.exists(BACKUP): return None
    if not sys.platform.startswith("win"):   # decrypt to stdout (captured in memory) — no plaintext key temp file
        rc, out = _age_pw(["-d", BACKUP], pw)
        m = re.search(r"AGE-SECRET-KEY-1[0-9A-Z]+", out or "")
        return m.group(0) + "\n" if rc == 0 and m else None
    tout = tempfile.NamedTemporaryFile(delete=False, suffix=".key").name
    try:
        rc, _ = _age_pw(["-d", "-o", tout, BACKUP], pw)
        return open(tout).read() if rc == 0 else None
    finally:
        try: os.remove(tout)
        except OSError: pass

def _write_backup(keytext, pw):
    """Encrypt keytext with pw and write to BACKUP (needs no plaintext key file)."""
    tk = tempfile.NamedTemporaryFile(delete=False, suffix=".key")
    tk.write(keytext.encode() if isinstance(keytext, str) else keytext); tk.close()
    tmp = BACKUP + ".new"
    try:
        if os.path.exists(tmp): os.remove(tmp)
        rc, err = _age_pw(["-p", "-o", tmp, tk.name], pw, confirm=True)
        if rc: raise RuntimeError(err.strip() or "backup could not be created")
        os.replace(tmp, BACKUP)
    finally:
        try: os.remove(tk.name)
        except OSError: pass

def _agents_data():
    return json.load(open(AGENTS)) if os.path.exists(AGENTS) else None
def _save_agents(d):
    with open(AGENTS, "w") as f: json.dump(d, f)
    os.chmod(AGENTS, 0o600)
def _agent_labels():
    d = _agents_data()
    return [t["label"] for t in (d["tokens"] if d else []) if t.get("source") == "agent" and not t.get("revoked")]

def mint_token(keytext, label, source="agent", ttl=None):
    """Mint a new unlock token: store hash + token-wrapped key, return the token VALUE (once)."""
    d = _agents_data() or {"salt": os.urandom(16).hex(), "tokens": []}
    tok = _secrets.token_urlsafe(24)
    kh = _scrypt(tok, bytes.fromhex(d["salt"])).hex()
    blob = base64.b64encode(_age_enc_bytes(keytext, tok)).decode()
    exp = (datetime.now(timezone.utc) + timedelta(seconds=ttl)).isoformat(timespec="seconds") if ttl else None
    d["tokens"] = [t for t in d["tokens"] if t["label"] != label]   # same label → replace
    d["tokens"].append({"label": label, "source": source, "kh": kh, "blob": blob,
                        "created": now_iso(), "expires": exp, "revoked": False})
    _save_agents(d); return tok

def _find_token(tok):
    """Find a valid/unexpired token record (including label/source); None if absent."""
    d = _agents_data()
    if not d or not tok: return None
    kh = _scrypt(tok.strip(), bytes.fromhex(d["salt"])).hex()
    now = now_iso()
    for e in d["tokens"]:
        if e.get("revoked"): continue
        if e.get("expires") and now > e["expires"]: continue
        if hmac.compare_digest(e["kh"], kh): return e
    return None

def resolve_token(tok):
    """Resolve a valid/unexpired token → age key text; None if absent."""
    e = _find_token(tok)
    if not e: return None
    try: return _age_unwrap(base64.b64decode(e["blob"]), tok.strip()).decode()
    except Exception: return None

def _mcp_agent():
    """Resolve CONCEALER_TOKEN and return (label, source); (None, None) if not registered."""
    e = _find_token(os.environ.get("CONCEALER_TOKEN", ""))
    return (e["label"], e.get("source")) if e else (None, None)

def _cli_actor():
    """CLI rate_gate key = the valid token's label (else 'cli'). AI agents using the
    CLI are subject to the same disclosure quota as via MCP; a human uses web/TUI without limit."""
    label, _ = _mcp_agent()
    return label or "cli"

def revoke_token(label):
    d = _agents_data()
    if not d: return 0
    n = len(d["tokens"]); d["tokens"] = [] if label == "all" else [t for t in d["tokens"] if t["label"] != label]
    _save_agents(d); return n - len(d["tokens"])

_UNLOCK_FOR = None   # "sync"/"pair" while those commands run: gates which token sources may open the vault
def _unlock_key():
    """Resolve the age private key text. In order: memory cache → CONCEALER_TOKEN →
    (plaintext file in an old vault=None) → master pw on the TTY. Error if not found."""
    global _KEY_CACHE
    if _KEY_CACHE: return _KEY_CACHE
    tok = os.environ.get("CONCEALER_TOKEN")
    if tok:
        src = (_find_token(tok) or {}).get("source")
        if src == "sync": sys.exit("this is a machine-sync token: it only serves the paired peer's sync.")
        if src == "sync-local" and _UNLOCK_FOR != "sync": sys.exit("this token is sync-only (concealer sync <host>).")
        if src == "agent" and _UNLOCK_FOR: sys.exit(f"agent tokens cannot run {_UNLOCK_FOR}; cron: concealer agent register <name> --sync-only")
        k = resolve_token(tok)
        if k: _KEY_CACHE = k; return k
        sys.exit("CONCEALER_TOKEN invalid/expired/revoked. New token: concealer unlock")
    if os.path.exists(KEY): return None   # legacy (non-hardened) vault: sops reads from the file
    if sys.stdin.isatty():                # interactive: unlock with master pw (cache for a single process)
        k = key_from_master(getpass.getpass("Master password (unlock): "))
        if not k: sys.exit("wrong password.")
        _KEY_CACHE = k; return k
    sys.exit("locked: no CONCEALER_TOKEN. Human: 'concealer unlock', agent: 'concealer agent register <name>'.")

def detect(dim):
    if dim in ("repo", "project"):
        r = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
        return os.path.basename(r.stdout.strip()) if r.returncode == 0 else os.path.basename(os.getcwd())
    return ""

# ---------------- setup / password ----------------
def _tty(): return sys.stdout.isatty()
def _c(s, code):   # ANSI color only on a TTY; plain text when piped/redirected
    return f"\033[{code}m{s}\033[0m" if _tty() else s
def _banner():
    # init/onboarding header: UTF-8 block logo (accent amber), otherwise plain. "er" brand accent:
    # the whole logo is printed in the accent color (coloring a single letter in block art isn't practical).
    utf8 = (sys.stdout.encoding or "").lower().startswith("utf")
    art = _LOGO if utf8 else ["concealer"]
    for ln in art: print(_c(ln, "38;5;203;1"))   # amber, bold
    print(_c("  local-only secret manager  ·  v" + VERSION, "38;5;203"))
    print()

def init(force=False):
    # A hardened vault has no KEY on disk (only BACKUP) — checking KEY alone let `init` walk straight
    # over an existing vault and generate a fresh keypair, orphaning the secrets. Check both.
    if (os.path.exists(KEY) or os.path.exists(BACKUP)) and not force:
        sys.exit("already set up.\nto reinstall: concealer init --force")
    _banner()
    print(_c("Setting up vault…", "1") + f"  ({HOME})\n")
    print(_c("Step 1/2", "38;5;203;1") + " — set a master password (this opens the vault; if lost you need a recovery code).")
    os.makedirs(os.path.dirname(KEY), exist_ok=True)
    if sys.platform.startswith("win"):
        import concealer_win; concealer_win.secure_dir(os.path.dirname(KEY))  # user-only ACL (chmod 0600 is a no-op on Windows)
    for f in (KEY, PUBKEY, BACKUP, MASTER):
        if os.path.exists(f): os.remove(f)
    r = subprocess.run(["age-keygen", "-o", KEY], capture_output=True, text=True)
    if r.returncode: sys.exit(f"key generation error: {scrub(r.stderr.strip())}")
    os.chmod(KEY, 0o600)
    pub = next(w for w in (r.stderr + r.stdout).split() if w.startswith("age1"))
    with open(PUBKEY, "w") as f: f.write(pub + "\n")
    keytext = open(KEY).read()
    pw = _ask_new_password()
    rc, err = _age_pw(["-p", "-o", BACKUP, KEY], pw, confirm=True)
    if rc: sys.exit(f"password-protected backup could not be created: {err.strip()}")
    write_master(pw); _audit_key()
    for f in (RECOVERY, AUDITHEAD, AGENTS):   # on a force reinstall clean up old leftovers
        if os.path.exists(f): os.remove(f)
    codes = _gen_codes(); write_recovery(codes, keytext)
    with open(SOPSCFG, "w") as f:
        f.write("creation_rules:\n  - path_regex: \\.enc\\.(yaml|yml|json)$\n" f'    age: "{pub}"\n')
    save({"secrets": []}); audit("init", source="cli")
    with open(os.path.join(HOME, ".gitignore"), "w") as f:
        f.write("keys/age-key.txt\nkeys/audit.key\nkeys/audit.head\nkeys/recovery.json\nkeys/agents.json\nkeys/ratestate.json\nkeys/backup.json\n")
    print("\n" + _c("Step 2/2", "38;5;203;1") + " — save the recovery codes (below, shown ONLY once).")
    _print_codes(codes)
    # key-at-rest: remove the age private key from disk (only the encrypted BACKUP remains).
    os.remove(KEY); audit("harden", source="cli")
    tok = mint_token(keytext, "cli", "cli", ttl=TOKEN_TTL)
    print("\n" + _c("✓ Done.", "38;5;40;1") + f"  KEY-AT-REST on — the vault key is no longer plaintext on disk.")
    print(f"  public key: {pub}\n")
    print(_c("Next steps:", "1"))
    print("  1) Add the CLI token to your shell (~%dh valid, refresh: eval \"$(concealer unlock)\"):" % (TOKEN_TTL // 3600))
    print("     " + _c(f"export CONCEALER_TOKEN={tok}", "38;5;203"))
    print("  2) Web UI (opens with the master password):   " + _c("concealer web", "38;5;203"))
    print("  3) Add your first secret:   " + _c('concealer set --name GITHUB_TOKEN --project myapp ghp_...', "38;5;203"))
    print("  4) Grant an AI agent access (MCP):   " + _c("concealer agent register <name>", "38;5;203"))
    print("  5) Set up automatic backups:   " + _c("concealer backup --dir <folder>", "38;5;203") + "  (details: web → Settings)")

def passwd():
    if not os.path.exists(BACKUP): sys.exit("run 'concealer init' first.")
    # 1st factor: current master password (decrypt both verifies and yields the key).
    keytext = key_from_master(getpass.getpass("Current master password: "))
    if not keytext: sys.exit("current password is wrong.")
    # 2nd factor: a valid recovery code (consumed) — master pw alone must not take over.
    d = _recovery_data()
    if not d or not d["codes"]:
        sys.exit("a recovery code is required but none are left/available.\n"
                 "  first generate a new set:  concealer recovery   (asks for the master password)")
    i = recovery_index(getpass.getpass("Recovery code (2nd factor): "))
    if i is None: sys.exit("invalid recovery code.")
    pw = _ask_new_password()
    _write_backup(keytext, pw); write_master(pw); consume_recovery(i); audit("passwd", source="cli")
    left = len(_recovery_data()["codes"])
    print(f"master password updated. recovery codes left: {left}"
          + ("\n  UYARI: kod kalmadi → 'concealer recovery' ile yenile." if left == 0 else ""))

def recover():
    """Master password forgotten: decrypt the age key with a recovery code + set a new password."""
    if not os.path.exists(RECOVERY): sys.exit("no recovery.json; this vault was not set up with recovery codes.")
    code = getpass.getpass("Recovery code: ")
    i = recovery_index(code)
    if i is None: sys.exit("invalid recovery code.")
    blob = base64.b64decode(_recovery_data()["codes"][i]["blob"])
    try: keytext = _age_unwrap(blob, code.strip()).decode()
    except Exception as ex: sys.exit(f"decrypt error: {ex}")
    if os.path.exists(KEY):                       # legacy vault: write the missing key file back
        with open(KEY, "w") as f: f.write(keytext)
        os.chmod(KEY, 0o600)
    pw = _ask_new_password()
    _write_backup(keytext, pw); write_master(pw); consume_recovery(i); audit("recover", source="cli")
    left = len(_recovery_data()["codes"])
    print(f"recovered; new master password set. recovery codes left: {left}"
          + ("\n  UYARI: kod kalmadi → 'concealer recovery' ile yenile." if left == 0 else ""))
    if not os.path.exists(KEY):
        global _KEY_CACHE; _KEY_CACHE = keytext
        print("  export CONCEALER_TOKEN=%s" % mint_token(keytext, "cli", "cli", ttl=TOKEN_TTL))

def recovery_regen():
    """Generate a new recovery code set (old ones become invalid). Requires the master password."""
    if not os.path.exists(BACKUP): sys.exit("run 'concealer init' first.")
    keytext = key_from_master(getpass.getpass("Master password: "))
    if not keytext: sys.exit("wrong password.")
    codes = _gen_codes(); write_recovery(codes, keytext); audit("recovery_regen", source="cli")
    _print_codes(codes)

def unlock():
    """Human: mint a TTL'd CLI token with the master pw. stdout=ONLY the export line (for eval)."""
    if not os.path.exists(BACKUP): sys.exit("run 'concealer init' first.")
    keytext = key_from_master(getpass.getpass("Master password: "))
    if not keytext: sys.exit("wrong password.")
    tok = mint_token(keytext, "cli", "cli", ttl=TOKEN_TTL); audit("unlock", source="cli")
    sys.stderr.write(f"CLI token generated (~{TOKEN_TTL // 3600 or 1}h). Run:  eval \"$(concealer unlock)\"\n")
    exp = int(datetime.now(timezone.utc).timestamp()) + TOKEN_TTL   # for the shell auto-unset hook
    print(f"export CONCEALER_TOKEN={tok}")
    print(f"export CONCEALER_TOKEN_EXP={exp}")

# ---------------- agent auto-setup (detect installed AI agents, wire up MCP + skill) ----------------
SKILL_MD = """---
name: concealer
description: Local secret manager. Use whenever a task needs a credential, API key, token, or DB password. Never write plaintext secrets; inject them with run_with_secrets using least-privilege names.
---

# concealer — secrets policy

When you need a secret, use the concealer MCP tools — never hardcode, echo, or write a plaintext value.

- **Find names first:** `list_secrets` (project/repo/tag filtered) or `search_secrets`. Neither returns values.
- **Use a value:** `run_with_secrets` — secrets are injected into the child env and redacted from output. Always pass `names` with ONLY the secrets the command needs (least privilege), and scope narrowly (tenant/project/environment/repo).
- **Create/update:** `set_secret`.
- **Never** print, cat, echo, or write a secret value.
"""

def _mcp_env(tok):
    env = {"CONCEALER_TOKEN": tok}
    if HOME != _default_home(): env["CONCEALER_HOME"] = HOME   # non-default vault → tell the server where it is
    return env

def _mcp_server_obj(tok):
    """MCP server entry (JSON-config shape) pointing at this concealer + a per-agent token."""
    script = os.path.abspath(__file__)
    if sys.platform == "win32":   # a bare shebang path is not runnable on Windows
        return {"command": sys.executable, "args": [script, "mcp"], "env": _mcp_env(tok)}
    return {"command": script, "args": ["mcp"], "env": _mcp_env(tok)}

def _install_mcp_json(path, key, tok):
    """Merge a 'concealer' MCP server into a JSON config under top-level `key` (mcpServers/servers)."""
    path = os.path.expanduser(path)
    d = {}
    if os.path.exists(path):
        try: d = json.load(open(path)) or {}
        except Exception: d = {}
    servers = d.get(key)
    if not isinstance(servers, dict): servers = {}
    servers["concealer"] = _mcp_server_obj(tok)
    d[key] = servers
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w") as f: json.dump(d, f, indent=2)
    return path

def _install_mcp_toml(path, tok):
    """Append a [mcp_servers.concealer] block to a TOML config (Codex). ponytail: no TOML parse — if a
    concealer block already exists we leave it (edit by hand); dedup would need a real TOML parser."""
    path = os.path.expanduser(path); script = os.path.abspath(__file__)
    cur = open(path).read() if os.path.exists(path) else ""
    if "[mcp_servers.concealer]" in cur: return path + " (already present, unchanged)"
    cmd, args = (json.dumps(sys.executable), [script, "mcp"]) if sys.platform == "win32" else (json.dumps(script), ["mcp"])
    block = f"\n[mcp_servers.concealer]\ncommand = {cmd}\nargs = {json.dumps(args)}\n\n[mcp_servers.concealer.env]\nCONCEALER_TOKEN = {json.dumps(tok)}\n"
    if HOME != _default_home(): block += f"CONCEALER_HOME = {json.dumps(HOME)}\n"
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "a") as f: f.write(block)
    return path

def _install_claude_code(tok):
    """Prefer the `claude` CLI (authoritative for user scope); fall back to writing ~/.claude.json."""
    script = os.path.abspath(__file__)
    if shutil.which("claude"):
        subprocess.run(["claude", "mcp", "remove", "--scope", "user", "concealer"], capture_output=True)  # idempotent
        cmd = ["claude", "mcp", "add", "--scope", "user", "concealer", "--env", f"CONCEALER_TOKEN={tok}"]
        if HOME != _default_home(): cmd += ["--env", f"CONCEALER_HOME={HOME}"]
        cmd += ["--", script, "mcp"]
        r = subprocess.run(cmd, capture_output=True, text=True)
        if r.returncode: raise RuntimeError(scrub(r.stderr.strip() or r.stdout.strip() or "claude mcp add failed"))
        return "via claude CLI (user scope)"
    return _install_mcp_json("~/.claude.json", "mcpServers", tok)

def _install_skill():
    """Write the concealer skill for Claude Code (~/.claude/skills/concealer/SKILL.md)."""
    d = os.path.expanduser("~/.claude/skills/concealer")
    os.makedirs(d, exist_ok=True)
    p = os.path.join(d, "SKILL.md")
    with open(p, "w") as f: f.write(SKILL_MD)
    return p

def _agent_defs():
    mac = sys.platform == "darwin"
    desktop = "~/Library/Application Support/Claude/claude_desktop_config.json" if mac else "~/AppData/Roaming/Claude/claude_desktop_config.json"
    return [
        {"id": "claude-code", "name": "Claude Code", "skill": True,
         "detect": lambda: bool(shutil.which("claude")) or os.path.exists(os.path.expanduser("~/.claude.json")),
         "install": _install_claude_code},
        {"id": "cursor", "name": "Cursor",
         "detect": lambda: os.path.isdir(os.path.expanduser("~/.cursor")),
         "install": lambda tok: _install_mcp_json("~/.cursor/mcp.json", "mcpServers", tok)},
        {"id": "windsurf", "name": "Windsurf",
         "detect": lambda: os.path.isdir(os.path.expanduser("~/.codeium/windsurf")),
         "install": lambda tok: _install_mcp_json("~/.codeium/windsurf/mcp_config.json", "mcpServers", tok)},
        {"id": "gemini", "name": "Gemini CLI",
         "detect": lambda: bool(shutil.which("gemini")) or os.path.isdir(os.path.expanduser("~/.gemini")),
         "install": lambda tok: _install_mcp_json("~/.gemini/settings.json", "mcpServers", tok)},
        {"id": "claude-desktop", "name": "Claude Desktop",
         "detect": lambda: os.path.exists(os.path.expanduser(desktop)),
         "install": lambda tok: _install_mcp_json(desktop, "mcpServers", tok)},
        {"id": "codex", "name": "Codex CLI",
         "detect": lambda: bool(shutil.which("codex")) or os.path.isdir(os.path.expanduser("~/.codex")),
         "install": lambda tok: _install_mcp_toml("~/.codex/config.toml", tok)},
    ]

def _detect_agents():
    out = []
    for d in _agent_defs():
        try:
            if d["detect"](): out.append(d)
        except Exception: pass
    return out

def agent_install(a):
    """Auto-detect installed AI agents, then wire concealer's MCP server (+ skill) into the chosen ones."""
    opts = {x for x in a if x.startswith("-")}
    ids  = [x for x in a if not x.startswith("-")]
    mcp_only, skill_only, want_all = "--mcp-only" in opts, "--skill-only" in opts, "--all" in opts
    detected = _detect_agents()
    if not detected:
        sys.exit("no known AI agents detected (looked for Claude Code, Cursor, Windsurf, Gemini CLI, Claude Desktop, Codex).")
    det_ids = [d["id"] for d in detected]
    if ids:
        miss = [i for i in ids if i not in det_ids]
        if miss: print("not detected (skipped): " + ", ".join(miss))
        chosen = [d for d in detected if d["id"] in ids]
    elif want_all:
        chosen = detected
    elif not sys.stdin.isatty():
        sys.exit("non-interactive: pass agent ids or --all. detected: " + ", ".join(det_ids))
    else:
        print("Detected agents:")
        for i, d in enumerate(detected, 1):
            print(f"  {i}) {_c(d['name'], '1')}  [{d['id']}]" + ("  (+skill)" if d.get("skill") else ""))
        sel = input("Set up which? (numbers comma-sep, 'a'=all, blank=cancel): ").strip().lower()
        if not sel: print("cancelled."); return
        if sel == "a": chosen = detected
        else:
            idx = {int(p) - 1 for p in re.split(r"[\s,]+", sel) if p.isdigit() and 1 <= int(p) <= len(detected)}
            chosen = [detected[i] for i in sorted(idx)]
    if not chosen: print("nothing selected."); return
    keytext = key_from_master(getpass.getpass("Master password: ")) if not skill_only else "x"
    if not keytext: sys.exit("wrong password.")
    for d in chosen:
        try:
            if not skill_only:
                tok = mint_token(keytext, d["id"], "agent", ttl=None)   # same label → replaces old token
                where = d["install"](tok)
                audit("agent_mcp_install", key=d["id"], source="cli")
                print(f"  {_c('✓', '32')} {d['name']}: MCP configured → {where}")
            if d.get("skill") and not mcp_only:
                print(f"  {_c('✓', '32')} {d['name']}: skill installed → {_install_skill()}")
            elif skill_only:
                print(f"  {_c('–', '90')} {d['name']}: no skill support (skipped)")
        except Exception as e:
            print(f"  {_c('✗', '31')} {d['name']}: {scrub(str(e))}")
    print("\nRestart the agent(s) to load the MCP server. Revoke a token anytime: concealer agent revoke <id>")

def agent_cmd(a):
    """Agent tokens: register/list/revoke. An agent registers once, never asked for a password again."""
    sub = a[0] if a else "list"
    if sub == "install":
        return agent_install(a[1:])
    if sub == "register":
        so = "--sync-only" in a; wf = "--write-token-file" in a; a = [x for x in a if x not in ("--sync-only", "--write-token-file")]
        if wf and not so: sys.exit("--write-token-file is only for --sync-only tokens.")
        if len(a) >= 2 and not re.fullmatch(r"[A-Za-z0-9_.-]{1,64}", a[1]): sys.exit("bad agent name.")
        if len(a) < 2: sys.exit("usage: concealer agent register <name> [--sync-only]")
        keytext = key_from_master(getpass.getpass("Master password: "))
        if not keytext: sys.exit("wrong password.")
        tok = mint_token(keytext, a[1], "sync-local" if so else "agent", ttl=None)
        audit("agent_register", key=a[1], source="cli", detail="sync-only" if so else "")
        if so and wf:   # straight to a 0600 file (dir 0700) → never on screen or in shell history
            kd = os.path.dirname(AGENTS); os.chmod(kd, 0o700); tf = os.path.join(kd, f"{a[1]}.token")
            fd = os.open(tf, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600); os.write(fd, tok.encode()); os.close(fd); os.chmod(tf, 0o600)
            return print(f"sync-only token '{a[1]}' written to {tf} (0600).\n"
                         f'  cron: CONCEALER_TOKEN="$(cat {tf})" concealer sync <host>\n  (revoke: concealer agent revoke {a[1]})')
        if so:   # cron/launchd: can run `concealer sync` and nothing else (not get/run/MCP)
            return print(f"sync-only token '{a[1]}' (works only for 'concealer sync'):\n  CONCEALER_TOKEN={tok}\n"
                         f"  (revoke: concealer agent revoke {a[1]})")
        print(f"agent '{a[1]}' registered (long-lived, revocable token).")
        print("Add to the MCP server env (e.g. .mcp.json / claude config):")
        print(f'  "env": {{ "CONCEALER_TOKEN": "{tok}" }}')
        print(f"  (revoke: concealer agent revoke {a[1]})")
    elif sub == "revoke":
        if len(a) < 2: sys.exit("usage: concealer agent revoke <name|all>")
        n = revoke_token(a[1]); audit("agent_revoke", key=a[1], source="cli"); print(f"revoked tokens: {n}")
    else:
        d = _agents_data()
        if not d or not d["tokens"]: print("no tokens."); return
        for t in d["tokens"]:
            st = "revoked" if t["revoked"] else (("expires " + t["expires"]) if t["expires"] else "suresiz")
            print(f"  {t['label']:16} {t['source']:6} {st:30} created {t['created']}")

def harden():
    """Migrate an old (plaintext-key) vault to key-at-rest: remove age-key.txt, mint a CLI token."""
    if not os.path.exists(BACKUP): sys.exit("run 'concealer init' first.")
    if not os.path.exists(KEY): print("already hardened (no plaintext key on disk)."); return
    keytext = key_from_master(getpass.getpass("Master password: "))
    if not keytext: sys.exit("wrong password.")
    os.remove(KEY); audit("harden", source="cli")
    gi = os.path.join(HOME, ".gitignore")           # an old init may not have written the agents.json line
    try:
        cur = open(gi).read() if os.path.exists(gi) else ""
        miss = [ln for ln in ("keys/agents.json", "keys/recovery.json", "keys/audit.head", "keys/ratestate.json", "keys/backup.json") if ln not in cur]
        if miss:
            with open(gi, "a") as f: f.write("\n".join(miss) + "\n")
    except OSError: pass
    tok = mint_token(keytext, "cli", "cli", ttl=TOKEN_TTL)
    print("hardened: the plaintext vault key was removed from disk (only the encrypted copy remains).")
    print(f"  export CONCEALER_TOKEN={tok}   (~{TOKEN_TTL // 3600}h; agent: concealer agent register <name>)")

# ---------------- injection ----------------
def env_key(name, field=None):
    """Sanitize a secret (+optional field) name into a valid POSIX env identifier.
    Upper-case; any char outside [A-Z0-9_] -> _; a leading digit gets a _ prefix.
    Without this, a name like 'grafana-prod' emits 'grafana-prod_PASSWORD', which
    is not a valid shell identifier and cannot be referenced by the child (see §3)."""
    raw = name if field is None else f"{name}_{field}"
    s = re.sub(r"[^A-Za-z0-9_]", "_", raw).upper()
    if s and s[0].isdigit(): s = "_" + s
    return s or "_"

def collect_secrets(target, d=None, names=None):
    """Collect secrets matching the target scopes as {ENV_KEY: value} (most specific wins).
    names: if given (set/list of secret names), inject ONLY those — least-privilege, so a
    command pulls just the secret it needs instead of the whole scope."""
    d = d or load(); chosen = {}
    names = set(names) if names else None
    for e in live(d):   # tombstones keep name+scope but no value — they must not shadow the live record
        if names is not None and e["name"] not in names: continue
        spec = 0; ok = True
        for dim in DIMS:
            ev = e[dim]
            if ev == "": continue
            if target.get(dim, "") == ev: spec += 1
            else: ok = False; break
        if not ok: continue
        if e["name"] not in chosen or spec > chosen[e["name"]][0]:
            chosen[e["name"]] = (spec, e)
    kv = {}; srcmap = {}   # env_key -> source label, to catch two secrets colliding onto one identifier
    for name, (sp, e) in chosen.items():
        base = e.get("env_alias") or name   # owner may pin a stable identifier base
        if e["type"] == "api_key":
            pairs = [(env_key(base), str(e["fields"].get("value", "")), name)]
        else:
            pairs = [(env_key(base, fn), str(fv), f"{name}.{fn}") for fn, fv in e["fields"].items()]
        for k, v, src in pairs:
            if k in kv and srcmap[k] != src:
                raise ValueError(f"env-name collision: '{srcmap[k]}' and '{src}' both map to {k}; set an env_alias to disambiguate")
            kv[k] = v; srcmap[k] = src
    return kv, d, [e for sp, e in chosen.values()]

def inject_env(target, source="cli", actor=None, command=None, gate=None, names=None):
    """If gate=<agent label> is given, injection passes through rate_gate(atomic) — if the quota is exceeded
    it returns (None, d, note) and NO secret is injected. If command is given, the executed command
    (redacted) is added to the audit detail. names: restrict injection to these secret names."""
    kv, d, recs = collect_secrets(target, names=names)
    if gate is not None:
        allowed, note = rate_gate(gate, recs, atomic=True)
        if recs and not allowed:
            audit("inject_denied", key=",".join(sorted(e["name"] for e in recs)), source=source, detail=label(target), actor=actor)
            return None, d, note
    env = dict(os.environ); env.update(kv)
    for k in ("CONCEALER_TOKEN", "CONCEALER_HOME", "CONCEALER_FILE", "CONCEALER_KEY"):
        env.pop(k, None)   # a child (e.g. via MCP run_with_secrets) must not reuse this process's vault access
    if kv:
        env["CONCEALER_INJECTED"] = ",".join(sorted(kv))   # names only (identifiers), never values — lets the child discover what was injected
        det = label(target)
        if command is not None: det = redact(f"{det} ↦ {command}", d)   # command goes to audit; the secret value doesn't leak
        audit("inject", key=",".join(sorted(kv)), source=source, detail=det, actor=actor)
    return env, d, note if gate is not None else None

# ---------------- deploy / render to target formats ----------------
DEPLOY_TARGETS = ["dotenv", "export", "docker", "json", "k8s", "aws-secrets", "aws-ssm", "github"]
def deploy_render(scope, target):
    """Render secrets matching the scope to text for the selected deploy target (produces commands/manifest)."""
    kv, d, _ = collect_secrets(scope)
    stem = "-".join(scope.get(x) for x in DIMS if scope.get(x)) or "concealer"
    return _render_target(kv, stem, target)

def deploy_render_one(e, target):
    """Render a single secret for the selected deploy target (row-level Deploy)."""
    base = e.get("env_alias") or e["name"]
    if e["type"] == "api_key":
        kv = {env_key(base): str(e["fields"].get("value", ""))}
    else:
        kv = {env_key(base, fn): str(fv) for fn, fv in e["fields"].items()}
    stem = "-".join(e.get(x) for x in DIMS if e.get(x)) or e["name"]
    return _render_target(kv, stem, target)

def _render_target(kv, stem, target):
    if target == "dotenv": return "\n".join(f"{k}={v}" for k, v in kv.items())
    if target == "export": return "\n".join(f"export {k}={shlex.quote(v)}" for k, v in kv.items())
    if target == "docker": return " ".join(f"-e {k}={shlex.quote(v)}" for k, v in kv.items())
    if target == "json":   return json.dumps(kv, indent=2)
    if target == "k8s":
        body = "\n".join(f"  {k}: {base64.b64encode(v.encode()).decode()}" for k, v in kv.items())
        return f"apiVersion: v1\nkind: Secret\nmetadata:\n  name: {stem}\ntype: Opaque\ndata:\n{body}"
    if target == "aws-secrets":
        return "\n".join(
            f"aws secretsmanager put-secret-value --secret-id {stem}/{k} --secret-string {shlex.quote(v)} \\\n"
            f"  || aws secretsmanager create-secret --name {stem}/{k} --secret-string {shlex.quote(v)}"
            for k, v in kv.items())
    if target == "aws-ssm":
        return "\n".join(f"aws ssm put-parameter --name /{stem}/{k} --type SecureString --value {shlex.quote(v)} --overwrite"
                         for k, v in kv.items())
    if target == "github":
        return "\n".join(f"gh secret set {k} --body {shlex.quote(v)}" for k, v in kv.items())
    return "unknown target"

def redact(text, d):
    for e in secs(d):
        for fn, fv in e["fields"].items():
            if fv and rec_field_secret(e, fn):   # record-aware: redact override + embedded-credential values too
                text = text.replace(str(fv), "***REDACTED***")
    return text

# ---------------- TUI (curses) ----------------
# ANSI-Shadow "CONCEALER" banner (big) + a compact fallback for narrow terminals.
_LOGO = [
    " ██████╗ ██████╗ ███╗   ██╗ ██████╗███████╗ █████╗ ██╗     ███████╗██████╗ ",
    "██╔════╝██╔═══██╗████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝██╔══██╗",
    "██║     ██║   ██║██╔██╗ ██║██║     █████╗  ███████║██║     █████╗  ██████╔╝",
    "██║     ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██║██║     ██╔══╝  ██╔══██╗",
    "╚██████╗╚██████╔╝██║ ╚████║╚██████╗███████╗██║  ██║███████╗███████╗██║  ██║",
    " ╚═════╝ ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═╝  ╚═╝╚══════╝╚══════╝╚═╝  ╚═╝",
]

_TUI_UTF8 = True   # are curses UTF-8 box-drawing chars safe (by locale, tui() sets this)

def tui():
    try: import curses, locale  # noqa: F401  (curses is Unix/macOS only)
    except ImportError: sys.exit("TUI needs the 'curses' module (Unix/macOS). Windows: pip install windows-curses.")
    # Try a UTF-8 locale for text (so chars like value/… encode correctly).
    utf8_locale = False
    for loc in ("", "en_US.UTF-8", "C.UTF-8", "UTF-8", "en_US.utf8"):
        try: locale.setlocale(locale.LC_ALL, loc)
        except locale.Error: continue
        try: enc = locale.nl_langinfo(locale.CODESET) or ""
        except Exception: enc = ""
        if enc.upper().replace("-", "") == "UTF8": utf8_locale = True; break
    # Use UTF-8 for box-drawing (┌│─) — BUT VS Code's integrated terminal (xterm.js) drops these
    # glyphs; draw ASCII (+-|) there. Force on/off manually with CONCEALER_TUI_ASCII=1/0.
    global _TUI_UTF8
    ascii_env = os.environ.get("CONCEALER_TUI_ASCII")
    if ascii_env in ("1", "true", "yes"): _TUI_UTF8 = False
    elif ascii_env in ("0", "false", "no"): _TUI_UTF8 = True
    else: _TUI_UTF8 = utf8_locale and os.environ.get("TERM_PROGRAM") != "vscode"
    # The TUI reveals secrets, so it ALWAYS requires the master password — it ignores any
    # CONCEALER_TOKEN in the environment (parity with the web UI, which unlocks per session).
    # Without this a shell holding an unlock token would open the TUI with no prompt.
    global _KEY_CACHE
    if os.path.exists(BACKUP):        # hardened vault: force a fresh master-pw unlock, bypassing the token
        if not sys.stdin.isatty(): sys.exit("locked: the TUI needs a terminal to read the master password.")
        _KEY_CACHE = key_from_master(getpass.getpass("Master password (unlock): "))
        if not _KEY_CACHE: sys.exit("wrong password.")
    d = load()                       # key resolved above (hardened) or read from the legacy plaintext file
    try:
        curses.wrapper(_tui_main, d)
    finally:
        # Defense-in-depth: curses already uses alternate-screen (?1049), but with iTerm2's
        # "Save lines to scrollback in alternate screen mode" setting on, TUI frames get
        # copied into the real scrollback → on exit secrets stay visible when scrolled up.
        # Not trusting the terminal setting, WE clear scrollback + screen on exit.
        # \033[3J = clear scrollback (xterm/iTerm2), \033[2J = screen, \033[H = cursor home.
        try:
            with open("/dev/tty", "w") as tty:
                tty.write("\033[H\033[2J\033[3J"); tty.flush()
        except Exception:
            sys.stdout.write("\033[H\033[2J\033[3J"); sys.stdout.flush()

def _tui_glyphs(u8):
    if u8:
        return {"tl": "┌", "tr": "┐", "bl": "└", "br": "┘", "h": "─", "v": "│",
                "lt": "├", "rt": "┤", "cur": "▸ ", "on": "◉ ", "off": "○ ", "ud": "↕"}
    return {"tl": "+", "tr": "+", "bl": "+", "br": "+", "h": "-", "v": "|",
            "lt": "+", "rt": "+", "cur": "> ", "on": "* ", "off": ". ", "ud": "^"}

# In ASCII mode (VS Code etc.) fold every drawn string down to ASCII in one place — no Unicode escapes.
_ASCII_MAP = str.maketrans({
    "┌": "+", "┐": "+", "└": "+", "┘": "+", "├": "+", "┤": "+", "─": "-", "│": "|",
    "·": "-", "…": "..", "•": "*", "▸": ">", "◉": "*", "○": ".", "↕": "^", "▏": "|",
    "→": "->", "←": "<-", "↑": "^", "↓": "v", "—": "-", "–": "-", "’": "'", "“": '"', "”": '"'})

def _tui_palette(curses):
    """Color palette — web 'Covert' theme (redaction-red accent). For bars/selection
    A_REVERSE|acc is used: theme-independently it gives a red background + dark text
    (plain COLOR_BLACK stayed invisible on acc in some terminals)."""
    if curses.has_colors():
        curses.start_color(); curses.use_default_colors()
        acc_c = 203 if curses.COLORS >= 256 else curses.COLOR_RED   # redaction red (was amber 214)
        gray  = 245 if curses.COLORS >= 256 else curses.COLOR_WHITE
        curses.init_pair(1, acc_c, -1); curses.init_pair(2, gray, -1)
        curses.init_pair(3, curses.COLOR_GREEN, -1); curses.init_pair(4, curses.COLOR_RED, -1)
        curses.init_pair(5, curses.COLOR_CYAN, -1)
        curses.init_pair(6, gray, curses.COLOR_BLACK)   # OPAQUE black background for the modal
        acc, mut, ok, bad, typ = (curses.color_pair(i) for i in range(1, 6))
        fill = curses.color_pair(6)
    else:
        acc = curses.A_BOLD; mut = curses.A_DIM; ok = 0; bad = curses.A_BOLD; typ = 0; fill = 0
    return {"acc": acc, "mut": mut, "ok": ok, "bad": bad, "typ": typ, "fill": fill,
            "bar": acc | curses.A_REVERSE, "sel": acc | curses.A_REVERSE, "norm": 0}

_TYP_COLOR = {"api_key": "typ", "access_token": "typ", "jwt": "typ", "oauth": "typ",
              "database": "acc", "server": "acc", "ssh_key": "acc", "certificate": "acc",
              "website": "ok", "login": "ok", "wifi": "ok", "membership": "ok"}
CLIP_CLEAR = 45   # seconds — the copied value is cleared from the clipboard after this (same behavior as web)

# ---- TUI language table: EN source → TR translation (separate from web I18N, curses-specific).
# L() returns the en key unchanged if not in the map → "en" is the identity language, only "tr" is kept.
_TUI_TR = {
    "terminal too small": "terminal cok kucuk", "[masked]": "[maskeli]", "[REVEALED]": "[ACIK]",
    "%d/%d secrets   %s ": "%d/%d sir   %s ", "Search: ": "Arama: ",
    "type s to search": "aramak icin s", "  filters: %d": "  filtre: %d",
    "1·Filters": "1·Filtreler", "2·Secrets": "2·Sirlar", "3·Details": "3·Detaylar",
    "NAME": "AD", "TYPE": "TIP", "(no matches)": "(eslesme yok)", "no secret selected": "sir secili degil",
    "j/k pick · Enter/m reveal · c copy": "j/k sec · Enter/m goster · c kopyala",
    "m: reveal all": "m: tumunu goster", "m: hide all": "m: tumunu gizle",
    "Tab panels · s search · m reveal · a add · e edit · d del · r rotate · c copy · ? help · L lang · q quit":
        "Tab paneller · s ara · m goster · a ekle · e duzenle · d sil · r dondur · c kopyala · ? yardim · L dil · q cikis",
    # messages
    "hid %s": "%s gizlendi", "revealed %s": "%s gosterildi", "hidden": "gizlendi",
    "revealed all": "tumu gosterildi", "filters cleared": "filtreler temizlendi",
    "nothing to copy": "kopyalanacak sey yok", "no %s field": "%s alani yok", "reloaded": "yeniden yuklendi",
    "copied %s → clipboard (clears in %ds)": "%s panoya kopyalandi (%dsn sonra silinir)",
    "no clipboard tool found (pbcopy / xclip / wl-copy)": "pano araci yok (pbcopy / xclip / wl-copy)",
    "no secret field to rotate": "dondurulecek gizli alan yok", "rotate cancelled": "dondurme iptal edildi",
    "rotated: %s": "donduruldu: %s", "Rotate '%s' → random value?": "'%s' rastgele degere dondurulsun mu?",
    "confirm": "onay", "language: %s": "dil: %s",
    # add/edit/delete
    "New secret — name": "Yeni sir — ad", "add cancelled": "ekleme iptal edildi", "Type": "Tip",
    "bad field name (looks like a secret value)": "gecersiz alan adi (bir secret degeri gibi gorunuyor)",
    "field name  (blank = done)": "alan adi  (bos = bitti)", "%s value": "%s degeri",
    "project (optional)": "proje (istege bagli)", "env (optional)": "ortam (istege bagli)",
    "added: %s": "eklendi: %s", "edit cancelled (not saved)": "duzenleme iptal (kaydedilmedi)",
    "updated: %s": "guncellendi: %s", "new field name": "yeni alan adi", "Edit: %s": "Duzenle: %s",
    "+ add field": "+ alan ekle", "» save & close": "» kaydet & kapat", "edit value": "degeri duzenle",
    "set visibility": "gorunurluk ayarla", "cancel": "iptal", "Delete '%s'  (%s) ?": "'%s' silinsin mi?  (%s)",
    "delete cancelled": "silme iptal edildi", "deleted: %s": "silindi: %s",
    "masked — partial  (sk-D…xy)": "maskeli — kismi  (sk-D…xy)",
    "masked — full  (••••••••)": "maskeli — tam  (••••••••)", "visible — plain text": "gorunur — duz metin",
    "'%s' visibility": "'%s' gorunurluk",
    # help window
    "conceal·er  —  keyboard": "conceal·er  —  klavye",
    "cycle panels   (1 / 2 / 3 jump to panel)": "panelleri degistir   (1 / 2 / 3 panele atla)",
    "move focus between panels": "paneller arasi odak tasi",
    "move   ·   g/G top/bottom   ·   PgUp/Dn, Ctrl-D/U page": "gez   ·   g/G bas/son   ·   PgUp/Dn, Ctrl-D/U sayfa",
    "search (live)   ·   Esc clears / exits": "ara (canli)   ·   Esc temizler / cikar",
    "Filters: toggle a facet   ·   x: clear all filters": "Filtreler: bir oge sec   ·   x: tum filtreleri temizle",
    "in Details panel": "Detaylar panelinde",
    "↑↓/j k pick a field   ·   Enter/m reveal that field": "↑↓/j k alan sec   ·   Enter/m o alani goster",
    "Secrets panel: reveal / hide ALL fields of the record": "Sirlar paneli: kaydin TUM alanlarini goster / gizle",
    "copy value · username · url  (clipboard clears in 45s)": "kopyala deger · kullanici · url  (pano 45sn'de silinir)",
    "add · edit · delete · rotate (random)": "ekle · duzenle · sil · dondur (rastgele)",
    "reload vault   ·   force redraw": "kasayi yukle   ·   yeniden ciz",
    "toggle language (TR / EN)": "dili degistir (TR / EN)",
    "this help   ·   q / Ctrl-Q quit": "bu yardim   ·   q / Ctrl-Q cikis",
}

def _tui_main(scr, data):
    import curses
    curses.curs_set(0); scr.keypad(True); scr.timeout(-1)
    try: curses.set_escdelay(25)
    except Exception: pass
    C = _tui_palette(curses)
    G = _tui_glyphs(_TUI_UTF8)   # ASCII box-drawing if no UTF-8 (e.g. VS Code terminal with C locale)
    st = {"d": data, "rows": [], "sel": 0, "top": 0, "term": "",
          "mode": "list", "focus": "list", "fsel": 0, "ftop": 0, "dtop": 0,
          "shown": set(), "dsel": 0,   # shown: field names revealed in this record · dsel: detail field cursor
          "active": {}, "fitems": [], "msg": "", "quit": False,
          "show_filters": True, "show_detail": True,
          # lang: saved preference → else OS locale (LANG=tr* → tr) → else en. Changes with 'L'.
          "lang": CFG.get("lang") or ("tr" if os.environ.get("LANG", "").lower().startswith("tr") else "en")}
    def L(s, *a):   # translate the EN source to the active language; fill %s/%d templates
        if st["lang"] == "tr": s = _TUI_TR.get(s, s)
        return (s % a) if a else s
    def FOCUS():   # focus ring by visible panels (in a narrow terminal don't focus a hidden panel)
        r = ["list"]
        if st["show_filters"]: r.insert(0, "filters")
        if st["show_detail"]: r.append("detail")
        return r

    # ---- draw helpers ----
    def put(y, x, s, attr=0, maxw=None):
        if y < 0 or x < 0: return
        s = str(s)
        if not _TUI_UTF8:   # ASCII mode (VS Code etc.): fold all Unicode in one place
            s = s.translate(_ASCII_MAP).encode("ascii", "replace").decode("ascii")
        if maxw is not None:
            if maxw <= 0: return
            s = s[:maxw]
        try: scr.addstr(y, x, s, attr)
        except (curses.error, UnicodeError, ValueError): pass   # edge/last-cell + non-UTF8 locale glyph

    def box(y, x, h, w, attr=0, title="", tattr=None):
        if h < 2 or w < 2: return
        put(y, x, G["tl"] + G["h"] * (w - 2) + G["tr"], attr)
        put(y + h - 1, x, G["bl"] + G["h"] * (w - 2) + G["br"], attr)
        for i in range(1, h - 1):
            put(y + i, x, G["v"], attr); put(y + i, x + w - 1, G["v"], attr)
        if title:
            put(y, x + 2, (G["rt"] + " " + title + " " + G["lt"])[:w - 4], tattr if tattr is not None else attr)

    # ---- filter / data ----
    def facets():
        d = st["d"]; out = []
        for dim, lbl in [("type", "Type"), ("collection", "Collection"), ("project", "Project"),
                         ("environment", "Env"), ("tenant", "Tenant"), ("repo", "Repo"), ("tags", "Tags")]:
            vals = {}
            for e in secs(d):
                if dim == "tags":
                    for tg in e.get("tags", []): vals[tg] = vals.get(tg, 0) + 1
                elif e.get(dim): vals[e[dim]] = vals.get(e[dim], 0) + 1
            if not vals: continue
            out.append(("hdr", dim, lbl, 0))
            for v in sorted(vals): out.append(("item", dim, v, vals[v]))
        return out

    def apply():
        d = st["d"]; sel = {}
        for dim in DIMS:
            if st["active"].get(dim): sel[dim] = ",".join(sorted(st["active"][dim]))
        typ = ",".join(sorted(st["active"].get("type", []))) or None
        tag = ",".join(sorted(st["active"].get("tags", []))) or None
        st["rows"] = filt(d, sel or None, tag, st["term"] or None, typ)
        cs = st["active"].get("collection")   # collection facet multi-select: OR incl. sub-path
        if cs: st["rows"] = [e for e in st["rows"]
                             if any(e.get("collection", "") == c or e.get("collection", "").startswith(c + "/") for c in cs)]
        st["sel"] = min(st["sel"], max(0, len(st["rows"]) - 1)); st["top"] = 0
        reset_detail()
        st["fitems"] = facets()   # always keep current (so toggle works in a narrow terminal too)
        st["fsel"] = min(st["fsel"], max(0, sum(1 for f in st["fitems"] if f[0] == "item") - 1))

    def reset_detail():   # on selection change: everything re-masked, cursor/scroll to top
        st["shown"] = set(); st["dsel"] = 0; st["dtop"] = 0

    def reload_(msg=""):
        try: st["d"] = load()
        except SystemExit as ex: st["msg"] = scrub(ex); return
        apply(); st["msg"] = msg

    def cur():
        return st["rows"][st["sel"]] if st["rows"] else None

    def nfilters():
        return sum(len(v) for v in st["active"].values())

    # ---- clipboard ----
    def clip(val, what):
        if sys.platform.startswith("win"):
            try:
                subprocess.run(["clip"], input=str(val), text=True, check=True)  # clip.exe reads stdin
                # auto-clear after CLIP_CLEAR seconds via a detached, hidden PowerShell
                subprocess.Popen(["powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command",
                                  f"Start-Sleep {CLIP_CLEAR}; Set-Clipboard -Value ' '"],
                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                e = cur()
                if e: audit("copy", key=e["name"], source="tui", detail=what)
                st["msg"] = L("copied %s → clipboard (clears in %ds)", what, CLIP_CLEAR)
            except Exception:
                st["msg"] = L("no clipboard tool found (pbcopy / xclip / wl-copy)")
            return
        for tool in (["pbcopy"], ["xclip", "-selection", "clipboard"], ["wl-copy"]):
            if shutil.which(tool[0]):
                try:
                    subprocess.run(tool, input=str(val), text=True, check=True)
                    subprocess.Popen(["sh", "-c", f"sleep {CLIP_CLEAR}; printf '' | {' '.join(tool)}"],
                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                    e = cur()
                    if e: audit("copy", key=e["name"], source="tui", detail=what)
                    st["msg"] = L("copied %s → clipboard (clears in %ds)", what, CLIP_CLEAR); return
                except Exception: pass
        st["msg"] = L("no clipboard tool found (pbcopy / xclip / wl-copy)")

    def secret_field(e):
        return next((f for f in e["fields"] if rec_field_secret(e, f)), None)

    def copy_value():
        e = cur()
        if not e: return
        if st["focus"] == "detail" and e["fields"]:   # in the detail panel: copy the selected field
            fn = list(e["fields"].keys())[max(0, min(st["dsel"], len(e["fields"]) - 1))]
            clip(e["fields"][fn], fn); return
        f = secret_field(e) or next(iter(e["fields"]), None)
        if f: clip(e["fields"][f], f)
        else: st["msg"] = L("nothing to copy")

    def copy_field(names, what):
        e = cur()
        if not e: return
        f = next((k for k in e["fields"] if k in names), None)
        if f: clip(e["fields"][f], f)
        else: st["msg"] = L("no %s field", what)

    # ---- modals ----
    def fill(y, x, h, w, attr):   # opaque background (so the area behind the modal isn't transparent)
        for r in range(h): put(y + r, x, " " * w, attr)

    def prompt(msg, default="", secret=False):
        curses.curs_set(1); H, W = scr.getmaxyx()
        bw = min(72, W - 4); by = H // 2 - 1; bx = (W - bw) // 2; buf = default
        while True:
            fill(by, bx, 3, bw, C["fill"]); box(by, bx, 3, bw, C["acc"], msg, C["acc"] | curses.A_BOLD)
            put(by + 1, bx + 1, " " * (bw - 2), C["fill"])
            shown = ("•" * len(buf)) if secret else buf
            put(by + 1, bx + 2, shown[-(bw - 4):], maxw=bw - 4)
            scr.refresh(); c = scr.getch()
            if c in (10, 13): curses.curs_set(0); return buf
            if c == 27: curses.curs_set(0); return None
            if c in (curses.KEY_BACKSPACE, 127, 8): buf = buf[:-1]
            elif 32 <= c < 127: buf += chr(c)

    def confirm(msg, danger=True):
        H, W = scr.getmaxyx(); bw = min(72, W - 4); a = C["bad"] if danger else C["acc"]
        fill(H // 2 - 1, (W - bw) // 2, 3, bw, C["fill"])
        box(H // 2 - 1, (W - bw) // 2, 3, bw, a, L("confirm"), a | curses.A_BOLD)
        put(H // 2, (W - bw) // 2 + 2, (msg + "  (y/N)")[:bw - 4], a | curses.A_BOLD); scr.refresh()
        return scr.getch() in (ord("y"), ord("Y"))

    def pick(title, labels, start=0):
        if not labels: return None
        i = min(start, len(labels) - 1)
        while True:
            H, W = scr.getmaxyx()
            bw = min(max(len(title) + 6, max(len(x) for x in labels) + 6), W - 4)
            bh = min(len(labels) + 2, H - 4); y = (H - bh) // 2; x = (W - bw) // 2
            fill(y, x, bh, bw, C["fill"]); box(y, x, bh, bw, C["acc"], title, C["acc"] | curses.A_BOLD)
            vis = bh - 2; topo = 0
            if len(labels) > vis: topo = max(0, min(i - vis // 2, len(labels) - vis))
            for r in range(vis):
                idx = topo + r
                if idx >= len(labels): break
                put(y + 1 + r, x + 1, (" " + labels[idx]).ljust(bw - 2),
                    C["sel"] if idx == i else C["fill"], bw - 2)
            scr.refresh(); c = scr.getch()
            if c in (27, ord("q")): return None
            if c in (10, 13): return i
            if c in (curses.KEY_DOWN, ord("j")): i = (i + 1) % len(labels)
            elif c in (curses.KEY_UP, ord("k")): i = (i - 1) % len(labels)
            elif c == ord("g"): i = 0
            elif c == ord("G"): i = len(labels) - 1

    def helpwin():
        rows = [
            ("Tab / Shift-Tab", L("cycle panels   (1 / 2 / 3 jump to panel)")),
            ("← → h l", L("move focus between panels")),
            ("↑ ↓ j k", L("move   ·   g/G top/bottom   ·   PgUp/Dn, Ctrl-D/U page")),
            ("s  /", L("search (live)   ·   Esc clears / exits")),
            ("Space / Enter", L("Filters: toggle a facet   ·   x: clear all filters")),
            ("", ""),
            (L("in Details panel"), L("↑↓/j k pick a field   ·   Enter/m reveal that field")),
            ("m", L("Secrets panel: reveal / hide ALL fields of the record")),
            ("c  u  w", L("copy value · username · url  (clipboard clears in 45s)")),
            ("a  e  d  r", L("add · edit · delete · rotate (random)")),
            ("M  C", L("move to collection · duplicate (copy)")),
            ("", ""),
            ("R  Ctrl-L", L("reload vault   ·   force redraw")),
            ("L", L("toggle language (TR / EN)")),
            ("?", L("this help   ·   q / Ctrl-Q quit")),
        ]
        H, W = scr.getmaxyx(); bw = min(74, W - 4); bh = min(len(rows) + 4, H - 2)
        y = (H - bh) // 2; x = (W - bw) // 2
        fill(0, 0, H, W, C["fill"])   # fill the whole screen with opaque black (so behind isn't transparent)
        box(y, x, bh, bw, C["acc"], L("conceal·er  —  keyboard"), C["acc"] | curses.A_BOLD)
        for r, (k, v) in enumerate(rows):
            if y + 2 + r >= y + bh - 1: break
            put(y + 2 + r, x + 3, k.ljust(18), C["acc"] | curses.A_BOLD, 18)
            put(y + 2 + r, x + 22, v, C["fill"] if not k and not v else (C["mut"]), bw - 24)
        scr.refresh(); scr.getch()

    def ask_visibility(fname, default_secret):
        # each field added/edited: choose hidden or visible + masking style
        opts = [L("masked — partial  (sk-D…xy)"), L("masked — full  (••••••••)"), L("visible — plain text")]
        idx = pick(L("'%s' visibility", fname), opts, 0 if default_secret else 2)
        if idx is None: return None
        if idx == 2: return {"secret": False}
        return {"secret": True, "mask": "full" if idx == 1 else "partial"}

    # ---- CRUD ----
    def add_flow():
        name = prompt(L("New secret — name"))
        if not name: st["msg"] = L("add cancelled"); return
        tkeys = sorted(TYPES.keys()); ti = pick(L("Type"), tkeys, tkeys.index("api_key"))
        if ti is None: st["msg"] = L("add cancelled"); return
        typ = tkeys[ti]
        e = {dim: "" for dim in DIMS}; e["name"] = name; e["type"] = typ; e["tags"] = []
        e["fields"] = {}; e["field_meta"] = {}
        tmpl = TYPES.get(typ)
        if tmpl:                                   # typed: template fields, with default secrecy
            for fn, kind in tmpl:
                v = prompt(f"{name} · {fn}", secret=(kind == "secret"))
                if v is None: st["msg"] = L("add cancelled"); return
                if v != "": e["fields"][fn] = v
        else:                                      # custom: free-form fields, ask visibility for each
            while True:
                fn = prompt(L("field name  (blank = done)"))
                if fn is None: st["msg"] = L("add cancelled"); return
                if not fn.strip(): break
                if _bad_field_name(fn): st["msg"] = L("bad field name (looks like a secret value)"); continue
                fm = ask_visibility(fn, field_is_secret("custom", fn))
                if fm is None: continue
                v = prompt(L("%s value", fn), secret=fm.get("secret", True))
                if v is None: continue
                e["fields"][fn] = v; e["field_meta"][fn] = fm
        proj = prompt(L("project (optional)")); env = prompt(L("env (optional)"))
        if proj: e["project"] = proj
        if env: e["environment"] = env
        secs(st["d"]).append(norm(e)); save(st["d"])
        audit("create", key=name, source="tui", detail=label(e)); reload_(L("added: %s", name))

    def edit_flow():
        e0 = cur()
        if not e0: return
        tgt = by_id(st["d"], e0["id"]); tgt.setdefault("field_meta", {}); i = 0
        while True:
            meta = [("name", tgt["name"]), ("type", tgt["type"]),
                    ("tags", ",".join(tgt["tags"])), ("collection", tgt.get("collection", "")),
                    ("project", tgt.get("project", "")),
                    ("environment", tgt.get("environment", "")), ("tenant", tgt.get("tenant", "")),
                    ("repo", tgt.get("repo", "")), ("url", tgt.get("url", "")),
                    ("notes", tgt.get("notes", ""))]
            fields = list(tgt["fields"].items())
            rows = meta + fields
            labels = []
            for j, (k, v) in enumerate(rows):
                if j >= len(meta) and rec_field_secret(tgt, k):
                    labels.append(f"{k:<14} • {rec_mask(tgt, k, v)}"[:62])
                else:
                    labels.append(f"{k:<14}   {v}"[:62])
            labels += [L("+ add field"), L("» save & close")]
            idx = pick(L("Edit: %s", tgt["name"]), labels, i)
            if idx is None: st["msg"] = L("edit cancelled (not saved)"); return
            i = idx
            if idx == len(labels) - 1:   # save
                tgt["updated"] = now_iso(); save(st["d"])
                audit("update", key=tgt["name"], source="tui"); reload_(L("updated: %s", tgt["name"])); return
            if idx == len(labels) - 2:   # add field
                fn = prompt(L("new field name"))
                if fn and fn.strip():
                    fm = ask_visibility(fn, field_is_secret(tgt["type"], fn))
                    if fm is not None:
                        tgt["fields"][fn] = prompt(L("%s value", fn), secret=fm.get("secret", True)) or ""
                        tgt["field_meta"][fn] = fm
                continue
            k = rows[idx][0]
            if idx < len(meta):   # split by section (not by name): a field name may collide with meta
                nv = prompt(f"{k}", tgt.get(k, "") if k != "tags" else ",".join(tgt["tags"]))
                if nv is None: continue
                if k == "tags": tgt["tags"] = [t for t in nv.split(",") if t.strip()]
                elif k == "type": tgt["type"] = nv if nv in TYPES else tgt["type"]
                elif k == "collection": tgt["collection"] = nv.strip().strip("/")
                else: tgt[k] = nv
            else:                 # field row: edit the value or the visibility
                act = pick(k, [L("edit value"), L("set visibility"), L("cancel")], 0)
                if act == 0:
                    nv = prompt(f"{k}", secret=rec_field_secret(tgt, k))
                    if nv is not None: tgt["fields"][k] = nv
                elif act == 1:
                    fm = ask_visibility(k, rec_field_secret(tgt, k))
                    if fm is not None: tgt["field_meta"][k] = fm

    def delete_flow():
        e = cur()
        if not e: return
        if not confirm(L("Delete '%s'  (%s) ?", e["name"], label(e))): st["msg"] = L("delete cancelled"); return
        tgt = by_id(st["d"], e["id"])
        if tgt: tombstone(st["d"], tgt); save(st["d"]); audit("delete", key=e["name"], source="tui")
        reload_(L("deleted: %s", e["name"]))

    def rotate_flow():
        e = cur()
        if not e: return
        f = secret_field(e)
        if not f: st["msg"] = L("no secret field to rotate"); return
        if not confirm(L("Rotate '%s' → random value?", e["name"])): st["msg"] = L("rotate cancelled"); return
        tgt = by_id(st["d"], e["id"]); tgt["fields"][f] = _secrets.token_urlsafe(32)
        tgt["updated"] = now_iso()
        if tgt.get("rotation", {}).get("every_days"): tgt["rotation"]["last"] = tgt["updated"]  # reset the clock
        save(st["d"]); audit("rotate", key=e["name"], source="tui")
        reload_(L("rotated: %s", e["name"]))

    def pick_collection(cur=""):
        # TUI equivalent of the web picker: existing collections + '(none)' + 'new…'. Returns: str path, or None (cancel).
        colls = sorted({e.get("collection", "") for e in secs(st["d"]) if e.get("collection")})
        opts = [L("(none)")] + colls + [L("+ new collection…")]
        start = colls.index(cur) + 1 if cur in colls else 0
        idx = pick(L("Collection"), opts, start)
        if idx is None: return None                       # cancel
        if idx == 0: return ""                            # (none)
        if idx == len(opts) - 1:                          # new one
            nv = prompt(L("new collection"), cur)
            return None if nv is None else nv.strip().strip("/")
        return opts[idx]                                  # existing selected

    def move_flow():   # move to collection (pick existing or type new; empty = out to root)
        e = cur()
        if not e: return
        nv = pick_collection(e.get("collection", ""))
        if nv is None: st["msg"] = L("move cancelled"); return
        tgt = by_id(st["d"], e["id"]); tgt["collection"] = nv; tgt["updated"] = now_iso()
        save(st["d"]); audit("update", key=e["name"], source="tui", detail=f"collection={tgt['collection'] or '-'}")
        reload_(L("moved: %s", e["name"]))

    def copy_flow():   # duplicate: a copy of the record (new id + new name + target collection)
        e = cur()
        if not e: return
        nn = prompt(L("Duplicate — new name"), e["name"] + "-copy")
        if not nn: st["msg"] = L("duplicate cancelled"); return
        nc = pick_collection(e.get("collection", ""))
        if nc is None: st["msg"] = L("duplicate cancelled"); return
        src = by_id(st["d"], e["id"])
        ne = norm({k: (list(v) if isinstance(v, list) else dict(v) if isinstance(v, dict) else v)
                   for k, v in src.items() if k != "id"})
        ne["name"] = nn; ne["collection"] = nc; ne["created"] = ne["updated"] = now_iso()
        secs(st["d"]).append(ne); save(st["d"])
        audit("create", key=nn, source="tui", detail=f"duplicate collection={ne['collection'] or '-'}")
        reload_(L("duplicated: %s", nn))

    # ---- screen drawing ----
    def draw():
        scr.erase(); H, W = scr.getmaxyx()
        if H < 8 or W < 30:
            put(0, 0, L("terminal too small"), C["bad"]); scr.refresh(); return
        # top bar (header)
        put(0, 0, " " * W, C["bar"])
        put(0, 1, "conceal", C["bar"] | curses.A_BOLD); put(0, 8, "er", C["bar"] | curses.A_BOLD | curses.A_UNDERLINE)
        home = HOME.replace(os.path.expanduser("~"), "~", 1)
        lockst = L("[REVEALED]") if st["shown"] else L("[masked]")
        right = L("%d/%d secrets   %s ", len(st["rows"]), len(secs(st["d"])), lockst)
        put(0, 11, f"· {home}", C["bar"], W - 12 - len(right))
        put(0, max(11, W - len(right)), right, C["bar"])
        # search row
        active_search = st["mode"] == "search"
        sattr = C["acc"] if active_search else C["mut"]
        fcount = L("  filters: %d", nfilters()) if nfilters() else ""
        put(1, 1, L("Search: "), C["acc"] if active_search else C["mut"])
        term = st["term"] + ("▏" if active_search else "")
        put(1, 9, term or (L("type s to search") if not active_search else ""),
            C["norm"] if st["term"] else C["mut"], W - 10 - len(fcount))
        put(1, W - len(fcount) - 1, fcount, C["mut"])
        # panel geometry
        by, bh = 2, H - 3
        show_filters = W >= 92
        show_detail = W >= 62
        st["show_filters"], st["show_detail"] = show_filters, show_detail
        if st["focus"] not in FOCUS(): st["focus"] = "list"   # reclaim focus from a hidden panel
        fw = 26 if show_filters else 0
        dw = max(30, (W - fw) * 2 // 5) if show_detail else 0
        lw = W - fw - dw
        fx, lx, dx = 0, fw, fw + lw
        draw_filters(fx, by, fw, bh) if show_filters else None
        draw_list(lx, by, lw, bh)
        draw_detail(dx, by, dw, bh) if show_detail else None
        draw_help(H, W)
        scr.refresh()

    def draw_filters(x, y, w, h):
        foc = st["focus"] == "filters"
        box(y, x, h, w, C["acc"] if foc else C["mut"], L("1·Filters"), (C["acc"] | curses.A_BOLD) if foc else C["mut"])
        items_idx = [i for i, f in enumerate(st["fitems"]) if f[0] == "item"]
        sel_line = items_idx[st["fsel"]] if items_idx and st["fsel"] < len(items_idx) else -1
        vis = h - 2
        if sel_line >= 0:
            if sel_line < st["ftop"]: st["ftop"] = sel_line
            if sel_line >= st["ftop"] + vis: st["ftop"] = sel_line - vis + 1
        for r in range(vis):
            li = st["ftop"] + r
            if li >= len(st["fitems"]): break
            kind, dim, val, cnt = st["fitems"][li]
            yy = y + 1 + r
            if kind == "hdr":
                put(yy, x + 1, val.upper()[:w - 2], C["acc"] | curses.A_BOLD, w - 2)
            else:
                on = val in st["active"].get(dim, set())
                mark = G["on"] if on else G["off"]
                text = f"{mark}{val}"
                cnts = str(cnt)
                if li == sel_line and foc:
                    put(yy, x + 1, " " * (w - 2), C["sel"])
                    put(yy, x + 1, text[:w - 3 - len(cnts)], C["sel"])
                    put(yy, x + w - 1 - len(cnts), cnts, C["sel"])
                else:
                    put(yy, x + 1, mark, C["acc"] if on else C["mut"])
                    put(yy, x + 3, val, (C["acc"] | curses.A_BOLD) if on else C["norm"], w - 4 - len(cnts))
                    put(yy, x + w - 1 - len(cnts), cnts, C["mut"])

    def draw_list(x, y, w, h):
        foc = st["focus"] == "list"
        box(y, x, h, w, C["acc"] if foc else C["mut"], L("2·Secrets"), (C["acc"] | curses.A_BOLD) if foc else C["mut"])
        rows = st["rows"]; iw = w - 2
        tcol = min(11, max(8, iw // 4)); scol = 0
        namew = max(1, iw - tcol - 1)   # a negative width raises ValueError in the format-spec; guard it
        put(y, x + 2 + 11, "", 0)
        # column headers
        put(y + 0, x + 2, "", 0)
        hdr = f"{L('NAME'):<{namew}} {L('TYPE'):<{tcol}}"
        # header on the first row, not inside the top line:
        vis = h - 3
        put(y + 1, x + 1, hdr[:iw], C["mut"] | curses.A_UNDERLINE)
        if not rows:
            put(y + 3, x + 2, L("(no matches)"), C["mut"])
        if st["sel"] < st["top"]: st["top"] = st["sel"]
        if st["sel"] >= st["top"] + (vis - 1): st["top"] = st["sel"] - (vis - 1) + 1
        for r in range(vis - 1):
            idx = st["top"] + r
            if idx >= len(rows): break
            e = rows[idx]; yy = y + 2 + r; sel = idx == st["sel"]
            nm = e["name"][:namew]; tp = e["type"][:tcol]
            if sel:
                put(yy, x + 1, " " * iw, C["sel"])
                put(yy, x + 1, (G["cur"] + nm)[:namew + 1], C["sel"] | curses.A_BOLD)
                put(yy, x + 2 + namew, tp, C["sel"])
            else:
                put(yy, x + 1, "  " + nm, C["norm"], namew + 1)
                tattr = C.get(_TYP_COLOR.get(e["type"], "mut"), C["mut"])
                put(yy, x + 2 + namew, tp, tattr, tcol)
        # scroll indicator
        if len(rows) > vis - 1:
            put(y + h - 1, x + w - 12, f"{G['rt']} {st['sel']+1}/{len(rows)} {G['lt']}", C["mut"])

    def draw_detail(x, y, w, h):
        foc = st["focus"] == "detail"
        box(y, x, h, w, C["acc"] if foc else C["mut"], L("3·Details"), (C["acc"] | curses.A_BOLD) if foc else C["mut"])
        e = cur(); iw = w - 3
        if not e:
            put(y + 2, x + 2, L("no secret selected"), C["mut"]); return
        # meta rows (non-selectable) — (key, value, color, fno=None)
        lines = [("name", e["name"], C["acc"] | curses.A_BOLD, None),
                 ("type", e["type"], C["typ"], None),
                 ("scope", label(e), C["norm"], None),
                 ("tags", ", ".join(e["tags"]) or "—", C["mut"], None)]
        if e.get("url"): lines.append(("url", e["url"], C["mut"], None))
        if e.get("notes"): lines.append(("notes", e["notes"], C["mut"], None))
        lines.append(("updated", e.get("updated", "")[:19].replace("T", " "), C["mut"], None))
        lines.append((None, None, None, None))   # separator
        # field rows (fno = which field; the detail cursor moves among these)
        fnames = list(e["fields"].keys())
        st["dsel"] = max(0, min(st["dsel"], len(fnames) - 1)) if fnames else 0
        fline = {}
        for fno, fn in enumerate(fnames):
            fv = e["fields"][fn]; sec = rec_field_secret(e, fn)
            revealed = (fn in st["shown"]) or not sec
            val = fv if revealed else rec_mask(e, fn, fv)
            col = C["ok"] if (revealed and sec) else (C["mut"] if sec else C["norm"])
            fline[fno] = len(lines); lines.append((fn, str(val), col, fno))
        vis = h - 3
        if foc and fnames:   # keep the selected field visible
            t = fline.get(st["dsel"], 0)
            if t < st["dtop"]: st["dtop"] = t
            if t >= st["dtop"] + vis: st["dtop"] = t - vis + 1
        st["dtop"] = max(0, min(st["dtop"], max(0, len(lines) - vis)))
        for r in range(vis):
            li = st["dtop"] + r
            if li >= len(lines): break
            k, val, col, fno = lines[li]; yy = y + 1 + r
            if k is None:
                put(yy, x + 1, G["h"] * iw, C["mut"]); continue
            if foc and fno is not None and fno == st["dsel"]:   # selected field row
                put(yy, x + 1, " " * iw, C["sel"])
                put(yy, x + 1, (G["cur"] + k)[:14], C["sel"] | curses.A_BOLD)
                put(yy, x + 1 + 14, val, C["sel"], iw - 14)
            else:
                put(yy, x + 1, (("  " if fno is not None else "") + k + "  ")[:14], C["acc"])
                put(yy, x + 1 + 14, val, col, iw - 14)
        hint = L("j/k pick · Enter/m reveal · c copy") if foc else (L("m: reveal all") if not st["shown"] else L("m: hide all"))
        foot = G["rt"] + " " + hint + " " + G["lt"]
        if len(lines) > vis: foot += f" {G['ud']}{st['dtop']+1}-{min(st['dtop']+vis, len(lines))}/{len(lines)}"
        put(y + h - 1, x + 2, foot, C["mut"], w - 4)

    def draw_help(H, W):
        y = H - 1
        put(y, 0, " " * W, C["bar"])
        hints = L("Tab panels · s search · m reveal · a add · e edit · d del · r rotate · c copy · ? help · L lang · q quit")
        put(y, 1, hints, C["bar"], W - 2)
        if st["msg"]:
            m = " " + st["msg"] + " "
            put(y, max(1, W - len(m) - 1), m[:W - 2], C["ok"] | curses.A_REVERSE)

    # ---- event loop ----
    def move_list(delta):   # on selection change everything masked + detail cursor/scroll to top
        st["sel"] = max(0, min(st["sel"] + delta, len(st["rows"]) - 1)); reset_detail()

    def reveal_field(e, fno):   # toggle a single field; if a hidden value is revealed drop to audit
        fnames = list(e["fields"].keys())
        if not fnames: return
        fn = fnames[max(0, min(fno, len(fnames) - 1))]
        if fn in st["shown"]: st["shown"].discard(fn); st["msg"] = L("hid %s", fn)
        else:
            st["shown"].add(fn); st["msg"] = L("revealed %s", fn)
            if rec_field_secret(e, fn): audit("get", key=e["name"], source="tui", detail=fn)

    def reveal_all(e):   # toggle all fields in the record
        if st["shown"]: st["shown"] = set(); st["msg"] = L("hidden")
        else:
            st["shown"] = set(e["fields"].keys()); st["msg"] = L("revealed all")
            if any(rec_field_secret(e, f) for f in e["fields"]):
                audit("get", key=e["name"], source="tui", detail="reveal all")

    def move_filter(delta):
        n = sum(1 for f in st["fitems"] if f[0] == "item")
        if n: st["fsel"] = max(0, min(st["fsel"] + delta, n - 1))

    def cycle_focus(step):
        ring = FOCUS()
        i = ring.index(st["focus"]) if st["focus"] in ring else ring.index("list")
        st["focus"] = ring[(i + step) % len(ring)]

    _splash(scr, C, curses)
    scr.clear()          # fully clear after the splash (no logo leftover)
    apply()
    while True:
        draw(); c = scr.getch()
        if c == curses.KEY_RESIZE:   # when a terminal like VS Code resizes: refresh ncurses + full redraw
            try: curses.update_lines_cols()
            except Exception: pass
            scr.clearok(True); continue
        H, W = scr.getmaxyx()
        # --- search mode ---
        if st["mode"] == "search":
            if c in (10, 13, curses.KEY_DOWN): st["mode"] = "list"; st["focus"] = "list"
            elif c == 27: st["mode"] = "list"; st["term"] = ""; apply()
            elif c in (curses.KEY_BACKSPACE, 127, 8): st["term"] = st["term"][:-1]; apply()
            elif c == 21: st["term"] = ""; apply()          # Ctrl-U
            elif 32 <= c < 127: st["term"] += chr(c); apply()
            continue
        st["msg"] = ""
        # --- global ---
        if c in (ord("q"), 17): break                       # q / Ctrl-Q
        elif c == ord("?"): helpwin()
        elif c in (ord("s"), ord("/")): st["mode"] = "search"   # s (TR keyboard friendly) or /
        elif c == ord("L"):                                  # change language (TR/EN) + persist
            st["lang"] = "tr" if st["lang"] == "en" else "en"
            CFG["lang"] = st["lang"]
            try: save_cfg(CFG)
            except Exception: pass
            st["msg"] = L("language: %s", st["lang"])
        elif c == 12: scr.clearok(True)                      # Ctrl-L: force full redraw
        elif c == 9: cycle_focus(1)                          # Tab
        elif c == curses.KEY_BTAB: cycle_focus(-1)           # Shift-Tab
        elif c == ord("1"): st["focus"] = "filters" if st["show_filters"] else st["focus"]
        elif c == ord("2"): st["focus"] = "list"
        elif c == ord("3"): st["focus"] = "detail" if st["show_detail"] else st["focus"]
        elif c in (curses.KEY_LEFT, ord("h")): cycle_focus(-1)
        elif c in (curses.KEY_RIGHT, ord("l")): cycle_focus(1)
        elif c == ord("m"):
            e = cur()
            if e: reveal_field(e, st["dsel"]) if st["focus"] == "detail" else reveal_all(e)
        elif c == ord("a"): add_flow()
        elif c == ord("e"): edit_flow()
        elif c == ord("d"): delete_flow()
        elif c == ord("r"): rotate_flow()
        elif c == ord("M"): move_flow()
        elif c == ord("C"): copy_flow()
        elif c == ord("c"): copy_value()
        elif c == ord("u"): copy_field({"username", "user", "member_id"}, "username")
        elif c == ord("w"): copy_field({"url", "web_url", "auth_url"}, "url")
        elif c == ord("R"): reload_(L("reloaded"))
        elif c == ord("x"):
            st["active"] = {}; apply(); st["msg"] = L("filters cleared")
        # --- focus-dependent ---
        elif st["focus"] == "filters":
            if c in (curses.KEY_DOWN, ord("j")): move_filter(1)
            elif c in (curses.KEY_UP, ord("k")): move_filter(-1)
            elif c == ord("g"): st["fsel"] = 0
            elif c == ord("G"): move_filter(10 ** 6)
            elif c in (10, 13, ord(" ")):
                items = [f for f in st["fitems"] if f[0] == "item"]
                if items and st["fsel"] < len(items):
                    _, dim, val, _ = items[st["fsel"]]
                    s = st["active"].setdefault(dim, set())
                    s.discard(val) if val in s else s.add(val)
                    if not s: st["active"].pop(dim, None)
                    apply()
        elif st["focus"] == "detail":   # in the detail panel j/k move between fields; Enter reveals
            e = cur(); nf = len(e["fields"]) if e else 0
            if c in (curses.KEY_DOWN, ord("j")): st["dsel"] = min(st["dsel"] + 1, max(0, nf - 1))
            elif c in (curses.KEY_UP, ord("k")): st["dsel"] = max(0, st["dsel"] - 1)
            elif c in (curses.KEY_NPAGE, 4): st["dsel"] = min(st["dsel"] + 5, max(0, nf - 1))
            elif c in (curses.KEY_PPAGE, 21): st["dsel"] = max(0, st["dsel"] - 5)
            elif c in (ord("g"), curses.KEY_HOME): st["dsel"] = 0
            elif c in (ord("G"), curses.KEY_END): st["dsel"] = max(0, nf - 1)
            elif c in (10, 13) and e: reveal_field(e, st["dsel"])
        else:   # list
            if c in (curses.KEY_DOWN, ord("j")): move_list(1)
            elif c in (curses.KEY_UP, ord("k")): move_list(-1)
            elif c == ord("g"): st["sel"] = 0; reset_detail()
            elif c == ord("G"): move_list(10 ** 6)
            elif c in (curses.KEY_NPAGE, 4): move_list((H - 6) or 5)     # PgDn / Ctrl-D
            elif c in (curses.KEY_PPAGE, 21): move_list(-((H - 6) or 5)) # PgUp / Ctrl-U
            elif c == curses.KEY_HOME: st["sel"] = 0; reset_detail()
            elif c == curses.KEY_END: move_list(10 ** 6)
            elif c in (10, 13): st["focus"] = "detail" if st["show_detail"] else "list"

def _splash(scr, C, curses):
    scr.erase(); H, W = scr.getmaxyx()
    if _TUI_UTF8 and W >= len(_LOGO[0]) + 2: art = _LOGO   # UTF-8 block logo
    else: art = ["c o n c e a l e r"]                      # ASCII fallback (non-UTF8 terminal)
    y0 = max(0, H // 2 - len(art) // 2 - 2)
    for i, ln in enumerate(art):
        x = max(0, (W - len(ln)) // 2)
        try: scr.addstr(y0 + i, x, ln[:W - 1], C["acc"] | curses.A_BOLD)
        except (curses.error, UnicodeError, ValueError): pass
    dot = "  ·  " if _TUI_UTF8 else "  -  "
    for txt, dy, at in [("local-only secret manager", len(art) + 1, C["mut"]),
                        (f"v{VERSION}", len(art) + 2, C["mut"]),
                        (f"press any key{dot}? for keyboard shortcuts", len(art) + 4, C["acc"])]:
        try: scr.addstr(y0 + dy, max(0, (W - len(txt)) // 2), txt, at)
        except (curses.error, UnicodeError, ValueError): pass
    scr.refresh(); scr.timeout(2500); scr.getch(); scr.timeout(-1)


# ---------------- CLI ----------------
def _flag(a, name):
    if name in a: i = a.index(name); v = a[i + 1]; del a[i:i + 2]; return v
    return None
def _sel(a):
    sel = {}
    for fl, dim in FLAGS.items():
        v = _flag(a, fl)
        if v is not None: sel[dim] = v
    return sel
def _print(rows):
    print(f"{'name':22} {'type':9} {'tenant':8} {'project':12} {'env':8} {'repo':14} tags")
    for e in rows:
        over = rotation_overdue(e); od = f"  ⟳{over}g gecikmis" if over is not None else ""
        col = f"  📁{e['collection']}" if e.get("collection") else ""
        print(f"{e['name']:22} {e['type']:9} {e['tenant']:8} {e['project']:12} "
              f"{e['environment']:8} {e['repo']:14} {','.join(e['tags'])}{col}{od}")

def _mkhelp():
    R = lambda syn, desc: f"  {syn:<46}{desc}"
    lines = [
        f"concealer {VERSION} — local-only secret manager   ·   alias: cer",
        "",
        "USAGE",
        "  concealer <command> [options]                 # short: cer <command>",
        "  most commands accept a scope: --tenant T  --project P  --env E  --repo R",
        "",
        "VAULT / KEY",
        R("init [--force]", "set up a new vault; prints master password, 8 recovery codes, CLI token"),
        R("unlock", "get a time-limited (TTL) token for a human, via the master password"),
        R("harden", "harden an old vault (remove the plaintext vault key from disk)"),
        R("passwd", "change the master password (requires a recovery code)"),
        R("recover", "access the vault with a recovery code (forgotten password)"),
        R("recovery", "regenerate the recovery-code set"),
        R("agent install [--all|--mcp-only|--skill-only] [ids]", "auto-detect agents, wire up MCP + skill"),
        R("agent register|list|revoke <name>", "long-lived, revocable token for agents"),
        R("agent register <name> --sync-only [--write-token-file]", "token that can only run 'sync' (cron); file: keys/<name>.token"),
        "",
        "SECRETS",
        R("list [term] [scope] [--tag X] [--type T]", "list records (masked)"),
        R("search <term>", "search across all fields"),
        R("get --name N [scope]", "print the secret value (must match exactly one)"),
        R("set --name N [--type T] <value | k=v ...>", "create/update (add --tags a,b for tags)"),
        R("rm --name N [scope]", "delete a record"),
        R("rotate --name N [new-value]", "rotate the value (random if none given)"),
        R("rotate --due [--dry]", "rotate every record whose rotation policy is overdue (cron-friendly)"),
        R("mv --name N [scope] --to-collection C", "move a record into a collection"),
        R("cp --name N [scope] --to-collection C [--as NEW]", "copy a record into a collection (new id)"),
        R("dims", "show the scope (tenant/project/env/repo) values in use"),
        R("leaks", "find reused (shared) secret values"),
        R("history [--purge]", "find (and optionally delete) secrets left in shell history"),
        "",
        "SCAN / DEPLOY",
        R("scan <folder> [--import] [--history] [--envvars] [scope]", "extract secrets from .env/files/history/env vars"),
        R("policy [list|check]", "list reminder policies / report violations (check: exit 1 if any — cron-friendly)"),
        R("expose [scope] [--offline]", "check secret values against known breaches (HIBP k-anonymity — value never sent)"),
        R("gitscan <repo>", "find secrets in git history / tracked files / logs + .gitignore gaps (local, read-only)"),
        R("deploy --target <t> [scope]", "render: dotenv|export|docker|json|k8s|aws-secrets|aws-ssm|github"),
        R("run [scope] <cmd...>", "inject secrets into env and run a command (no values leak)"),
        "",
        "TRANSFER / AUDIT / INTERFACE",
        R("export [file]", "export a password-protected .cerbak bundle"),
        R("import <bundle.cerbak> [--mode=overwrite|skip|duplicate]", "import a bundle / restore a .cerbak backup (conflict handling)"),
        R("backup [--dir D]", "write a .cerbak vault backup (uses the Settings backup password; for cron/launchd)"),
        R("pair <ssh-host> [--remote-cmd C]", "pair with another machine's vault over ssh (once; both master passwords)"),
        R("pair [--list] | pair --revoke <host>", "list / revoke machine pairings (revoke kills the sync token)"),
        R("sync <host> [--dry] [--allow-deletes] [--via H]", "encrypted two-way sync with a paired machine (cron-friendly)"),
        R("audit [verify]", "HMAC-chained audit log (verify: integrity check)"),
        R("audit anchor [--file F][--syslog][--webhook U]", "push head hash to an off-machine sink (tamper-evidence)"),
        R("config [key [val]]", "runtime settings (idle, confirm_ops)"),
        R("tui", "interactive terminal UI (arrow keys, search, add/del/reveal)"),
        R("web [port]", "serve the web UI + JSON API (default 8787)"),
        R("lan [lan_port [web_port]]", "reach the web UI from a phone on the same LAN (default 8788->8787)"),
        R("service install|uninstall|status", "run 'lan' automatically at login (launchd/systemd/Task) — phones auto-discover it"),
        R("mcp", "MCP stdio server (for agents; needs CONCEALER_TOKEN)"),
        R("chrome-extension", "register the Chrome extension's native host (one-time OS setup)"),
        R("version [--check] | help", "version (--check: look for a newer release) / this help"),
        "",
        "TYPES",
        "  api_key (default) · database · website · login · oauth · jwt · ssh_key · wifi · custom · …",
        "",
        "EXAMPLES",
        "  concealer init                                # run the 'export CONCEALER_TOKEN=…' line it prints",
        "  cer set --name openai --project web --env prod sk-DUMMY-123",
        "  cer get --name openai --project web --env prod",
        "  cer set --name pg --type database --project web \\",
        "      host=db.local port=5432 database=app username=app password=sk-DUMMY-pw",
        "  cer scan ./myrepo --history --import --project myrepo --env dev",
        "  cer run --project web --env prod npm run deploy",
        "  cer deploy --target dotenv --project web --env prod > .env",
        "  cer tui                                       # browse/search secrets in the terminal",
        "  cer web 8787                                  # http://localhost:8787 (unlock with master pw)",
        "  cer lan                                       # phone -> http://<host>.local:8788 (same LAN only)",
        "  cer agent register my-agent                   # prints CONCEALER_TOKEN=…",
        "  CONCEALER_TOKEN=… cer mcp",
        "",
        "ENVIRONMENT",
        R("CONCEALER_HOME", "vault directory (default: ~/.concealer; repo checkout: next to the script)"),
        R("CONCEALER_TOKEN", "CLI/MCP unlock token (init/unlock/agent register produce it)"),
        R("CONCEALER_IDLE", "web session idle-lock timeout (seconds)"),
        R("CONCEALER_SSH", "transport command for pair/sync (default: ssh)"),
        "",
        "Docs: https://github.com/fxerkan/concealer",
    ]
    return "\n".join(lines)
HELP = _mkhelp()

# External dependencies. The packaged installs (brew tap / scoop) pull them in; on a manual install
# point at the installer rather than naming the tools — no user-facing surface names them (see scrub()).
_DEPS = {"sops": "sops", "age": "age", "age-keygen": "age", "expect": "expect"}
_DEPS_DOC = "https://concealer.fxerkan.com/installation"
def _preflight():
    _win = sys.platform.startswith("win")
    deps = [b for b in _DEPS if not (_win and b == "expect")]  # Windows: pywinpty replaces expect
    missing = [b for b in deps if not shutil.which(b)]
    if _win:
        try: import winpty  # noqa: F401 — the ConPTY driver for the passphrase prompt (see concealer_win.py)
        except ImportError: missing.append("pywinpty")
    if not missing: return
    hint = "scoop install fxerkan/concealer" if _win else \
           "brew install fxerkan/tap/concealer" if shutil.which("brew") else None
    sys.exit("concealer is missing the components it encrypts with.\n" +
             (f"install everything together:  {hint}\nmanual setup: {_DEPS_DOC}"
              if hint else f"setup guide: {_DEPS_DOC}"))

# ---------------- Chrome extension: built-in native-messaging host + one-time setup ----------------
# The host lives INSIDE concealer (no separate script), so a brew/scoop install needs no extra files.
# `concealer chrome-extension` registers a launcher that runs `concealer native-host`; the extension
# popup calls it to start `concealer web` on demand.
_HOST_NAME = "com.concealer.host"
_EXT_DEV_ID = "bkogcelhpcfdfceaoickckmikhglgpae"   # deterministic ID from the repo manifest "key" (unpacked dev build)
_EXT_STORE_ID = "hecffnhjbhldmdpcnpkpcffmodnemdcj"    # Chrome Web Store item ID (published build)

def _stable_self():
    """Path to this script that survives an upgrade. `realpath(__file__)` resolves the
    package manager's symlink down to a versioned dir (Homebrew's Cellar/<ver>/libexec,
    scoop's app/<ver>) which the NEXT upgrade deletes — the registered native host then
    dies instantly ("Native host has exited"). A PATH entry is re-pointed on upgrade, so
    prefer it whenever it resolves to this same file."""
    real = os.path.realpath(__file__)
    for name in ("concealer", "cer"):
        p = shutil.which(name)
        try:
            if p and os.path.realpath(p) == real: return p
        except OSError: pass
    return real

def native_host():
    """Chrome native-messaging host (stdio). One request per launch:
    {"cmd":"ensure","port":8787} → start `concealer web <port>` if nothing is listening, then reply."""
    import struct, socket, time as _t
    def port_open(p):
        with socket.socket() as s:
            s.settimeout(0.3)
            try: s.connect(("127.0.0.1", p)); return True
            except OSError: return False
    def reply(o):
        b = json.dumps(o).encode()
        sys.stdout.buffer.write(struct.pack("@I", len(b))); sys.stdout.buffer.write(b); sys.stdout.buffer.flush()
    raw = sys.stdin.buffer.read(4)
    if len(raw) < 4: return
    n = struct.unpack("@I", raw)[0]
    try: msg = json.loads(sys.stdin.buffer.read(n).decode())
    except Exception: msg = {}
    if msg.get("cmd") != "ensure": return reply({"ok": False, "err": "unknown cmd"})
    port = int(msg.get("port") or 8787)
    def running_version():   # None if unreachable/old; version string otherwise
        try:
            with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/session", timeout=1) as r:
                return json.loads(r.read().decode()).get("version")
        except Exception: return None
    if port_open(port):
        v = running_version()
        if v == VERSION: return reply({"ok": True, "running": True, "port": port})
        # A server from a previous install is holding the port (e.g. its files were removed by
        # an upgrade → "webui.html not found"). Ask it to stop, then launch the current one.
        try: urllib.request.urlopen(urllib.request.Request(f"http://127.0.0.1:{port}/api/shutdown", data=b"", method="POST"), timeout=2).read()
        except Exception: pass
        for _ in range(20):
            if not port_open(port): break
            _t.sleep(0.15)
        if port_open(port):   # pre-fix server with no /api/shutdown → can't replace it automatically
            return reply({"ok": False, "err": f"an old concealer server (v{v or 'unknown'}) is on port {port}; quit it (or reboot) and reopen"})
    env = dict(os.environ); env["CONCEALER_NO_OPEN"] = "1"; env.setdefault("CONCEALER_WEB_IDLE_EXIT", "900")
    kw = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL, "stdin": subprocess.DEVNULL, "env": env}
    if os.name == "nt": kw["creationflags"] = 0x00000008 | 0x00000200  # DETACHED_PROCESS|CREATE_NEW_PROCESS_GROUP
    else: kw["start_new_session"] = True
    try: subprocess.Popen([sys.executable, _stable_self(), "web", str(port)], **kw)
    except Exception as e: return reply({"ok": False, "err": f"launch failed: {e}"})
    for _ in range(40):   # wait up to ~6s for it to bind
        if port_open(port): return reply({"ok": True, "running": True, "port": port, "started": True})
        _t.sleep(0.15)
    reply({"ok": False, "err": "server did not come up in time"})

def _chrome_state():   # persisted extra allowed-origin IDs (so re-runs keep dev IDs you've added)
    return os.path.join(HOME, "chrome_ext.json")
def _chrome_dir():     # where the launcher (and, on Windows, the manifest) live
    d = os.path.join(HOME, "chrome"); os.makedirs(d, exist_ok=True); return d

def _chrome_browser_targets():
    home = os.path.expanduser("~")
    if sys.platform == "darwin":
        base = os.path.join(home, "Library", "Application Support")
        subs = ["Google/Chrome", "Google/Chrome Beta", "Google/Chrome Canary", "Chromium",
                "BraveSoftware/Brave-Browser", "Microsoft Edge"]
    else:
        base = os.path.join(home, ".config")
        subs = ["google-chrome", "google-chrome-beta", "chromium", "BraveSoftware/Brave-Browser", "microsoft-edge"]
    return base, subs

def install_chrome_extension(args, quiet=False):
    """One-time OS setup so the Chrome extension can start `concealer web` on demand."""
    import stat, json as _json
    if "--uninstall" in args: return _chrome_uninstall()
    add = [args[i+1] for i, x in enumerate(args) if x == "--add-id" and i+1 < len(args)]
    # merge allowed IDs: built-in dev + store (once known) + previously-added + newly-added
    ids = {_EXT_DEV_ID}
    if _EXT_STORE_ID: ids.add(_EXT_STORE_ID)
    os.makedirs(HOME, exist_ok=True)
    if os.path.exists(_chrome_state()):
        try: ids |= set(_json.load(open(_chrome_state())).get("ids", []))
        except Exception: pass
    ids |= set(add)
    if "--list" in args:
        print("allowed extension IDs:"); [print("  " + i) for i in sorted(ids)]; return
    _json.dump({"ids": sorted(ids)}, open(_chrome_state(), "w"), indent=2)

    python = sys.executable or shutil.which("python3") or "python3"
    concealer = _stable_self()
    origins = [f"chrome-extension://{i}/" for i in sorted(ids)]
    man = {"name": _HOST_NAME, "description": "concealer native messaging host", "type": "stdio",
           "allowed_origins": origins}
    # Chrome launches native hosts with a minimal env → pin PATH (find sops/age) and CONCEALER_HOME.
    d = _chrome_dir()
    if os.name == "nt":
        launcher = os.path.join(d, "run_host.bat")
        lines = ['@echo off', f'set "PATH={os.environ.get("PATH","")}"']
        if os.environ.get("CONCEALER_HOME"): lines.append(f'set "CONCEALER_HOME={os.environ["CONCEALER_HOME"]}"')
        lines.append(f'"{python}" "{concealer}" native-host')
        open(launcher, "w", newline="\r\n").write("\r\n".join(lines) + "\r\n")
    else:
        launcher = os.path.join(d, "run_host.sh")
        lines = ["#!/bin/sh", f'export PATH="{os.environ.get("PATH","")}"']
        if os.environ.get("CONCEALER_HOME"): lines.append(f'export CONCEALER_HOME="{os.environ["CONCEALER_HOME"]}"')
        # Resolve again at run time: if the recorded path ever vanishes (reinstall, upgrade
        # to a differently-laid-out prefix), fall back to whatever is on PATH.
        lines += [f'CER="{concealer}"',
                  '[ -f "$CER" ] || CER="$(command -v concealer 2>/dev/null || command -v cer 2>/dev/null)"',
                  f'exec "{python}" "$CER" native-host']
        open(launcher, "w").write("\n".join(lines) + "\n")
        os.chmod(launcher, os.stat(launcher).st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
    man["path"] = launcher

    written = []
    if os.name == "nt":
        import winreg
        mpath = os.path.join(d, _HOST_NAME + ".json"); _json.dump(man, open(mpath, "w"), indent=2)
        for root in [r"Software\Google\Chrome\NativeMessagingHosts",
                     r"Software\Microsoft\Edge\NativeMessagingHosts",
                     r"Software\Chromium\NativeMessagingHosts"]:
            try:
                k = winreg.CreateKey(winreg.HKEY_CURRENT_USER, root + "\\" + _HOST_NAME)
                winreg.SetValueEx(k, "", 0, winreg.REG_SZ, mpath); winreg.CloseKey(k); written.append(root)
            except OSError as e: print(f"  skip {root}: {e}")
    else:
        base, subs = _chrome_browser_targets()
        targets = [os.path.join(base, s) for s in subs if os.path.isdir(os.path.join(base, s))] or [os.path.join(base, subs[0])]
        for t in targets:
            nh = os.path.join(t, "NativeMessagingHosts"); os.makedirs(nh, exist_ok=True)
            _json.dump(man, open(os.path.join(nh, _HOST_NAME + ".json"), "w"), indent=2); written.append(nh)

    if quiet: return
    print("✓ concealer Chrome extension native host registered.")
    print(f"  vault   : {os.environ.get('CONCEALER_HOME') or HOME}")
    print(f"  IDs     : {', '.join(sorted(ids))}")
    for w in written: print("  host    : " + w)
    print("\nNow open the concealer extension in Chrome — no need to type `cer web`.")
    print("Add a dev/unpacked build's ID:  concealer chrome-extension --add-id <extension-id>")

def _chrome_selfheal():
    """Repair a launcher left dangling by an upgrade. Package managers install into a
    versioned dir and delete the old one, so a launcher that recorded that dir stops
    working the moment you upgrade — Chrome only reports "Native host has exited". Any
    normal `concealer web` run rewrites it, so the extension heals without the user
    knowing why it broke."""
    try:
        f = os.path.join(HOME, "chrome", "run_host.bat" if os.name == "nt" else "run_host.sh")
        if not os.path.exists(f): return                    # never registered → nothing to heal
        body = open(f).read()
        want = _stable_self()
        if want in body: return
        paths = re.findall(r'"([^"]*concealer[^"]*)"', body)  # recorded script path(s)
        if paths and all(os.path.exists(p) for p in paths): return
        install_chrome_extension([], quiet=True)
    except Exception: pass                                  # never block the server on this

def _chrome_uninstall():
    removed = []
    for p in [os.path.join(_chrome_dir(), "run_host.sh"), os.path.join(_chrome_dir(), "run_host.bat"),
              os.path.join(_chrome_dir(), _HOST_NAME + ".json"), _chrome_state()]:
        if os.path.exists(p): os.remove(p); removed.append(p)
    if os.name == "nt":
        import winreg
        for root in [r"Software\Google\Chrome\NativeMessagingHosts",
                     r"Software\Microsoft\Edge\NativeMessagingHosts",
                     r"Software\Chromium\NativeMessagingHosts"]:
            try: winreg.DeleteKey(winreg.HKEY_CURRENT_USER, root + "\\" + _HOST_NAME); removed.append(root)
            except OSError: pass
    else:
        base, subs = _chrome_browser_targets()
        for s in subs:
            p = os.path.join(base, s, "NativeMessagingHosts", _HOST_NAME + ".json")
            if os.path.exists(p): os.remove(p); removed.append(p)
    print("removed:" if removed else "nothing to remove")
    for r in removed: print("  " + r)

def _vtuple(s):   # "v0.9.22" → (0,9,22); non-numeric parts drop to 0
    return tuple(int(p) if p.isdigit() else 0 for p in s.lstrip("vV").split("."))

def check_update():
    """On-demand only: ask GitHub for the latest release and compare. Off by default —
    concealer makes no network calls unless the user runs `version --check`."""
    url = "https://api.github.com/repos/fxerkan/concealer/releases/latest"
    try:
        req = urllib.request.Request(url, headers={"Accept": "application/vnd.github+json", "User-Agent": "concealer"})
        with urllib.request.urlopen(req, timeout=5) as r:
            tag = (json.loads(r.read().decode()).get("tag_name") or "").strip()
    except Exception:
        return print("  (couldn't reach the update server — check your connection)")
    if not tag: return print("  (no release info available)")
    if _vtuple(tag) > _vtuple(VERSION):
        print(f"  a newer version is available: {tag.lstrip('vV')}  (you have {VERSION})")
        print("  update with your package manager:  brew upgrade concealer  ·  scoop update concealer  ·  pip install -U concealer")
    else:
        print("  up to date")

def cli(argv):
    cmd = argv[0] if argv else "help"; a = argv[1:]
    if cmd in ("version", "--version", "-v"):
        print("concealer " + VERSION)
        if "--check" in a: check_update()   # opt-in, on-demand only — never runs automatically
        return
    if cmd in ("help", "--help", "-h", ""): return print(HELP)
    if cmd == "native-host": return native_host()
    if cmd == "sync-serve": return sync_serve()   # remote end of pair/sync over ssh: JSON in/out only, no preflight noise   # Chrome-invoked stdio host: no preflight (keeps stdout clean)
    _preflight()
    if cmd == "init": return init("--force" in a)
    if cmd == "passwd": return passwd()
    if cmd == "recover": return recover()
    if cmd == "recovery": return recovery_regen()
    if cmd == "unlock": return unlock()
    if cmd == "agent": return agent_cmd(a)
    if cmd in ("set", "add", "rm", "rotate", "mv", "cp", "import"):   # mutating: serialize with sync merges
        global _HELD_LOCK; _HELD_LOCK = _vault_lock(); _HELD_LOCK.__enter__()   # released at process exit
    if cmd == "pair": return pair_cmd(a)
    if cmd == "sync": return sync_cmd(a)
    if cmd == "harden": return harden()
    if cmd == "backup":
        # write a .cer using the (age-wrapped) password + folder from the auto-backup config — for cron/launchd.
        # Key access: CONCEALER_TOKEN (else master pw on a TTY). --dir temporarily overrides the folder.
        d = _flag(a, "--dir")
        if d: c = _backup_cfg(); c["dir"] = d; _save_backup_cfg(c)
        try: path = run_auto_backup()
        except Exception as ex: sys.exit(f"backup error: {ex}")
        return print(f"backup: {path}")
    if cmd == "tui": return tui()
    if cmd == "list":
        tag = _flag(a, "--tag"); coll = _flag(a, "--collection"); sel = _sel(a); typ = sel.pop("type", None)
        actor = _cli_actor()
        rows, note = rate_gate(actor, filt(load(), sel, tag, a[0] if a else None, typ, coll))
        audit("list", source="cli", detail=json.dumps(sel), actor=actor)
        _print(rows)
        if note: sys.stderr.write(note.lstrip("\n") + "\n")
    elif cmd == "search":
        actor = _cli_actor()
        rows, note = rate_gate(actor, filt(load(), term=a[0]))
        audit("search", source="cli", detail=a[0] if a else "", actor=actor)
        _print(rows)
        if note: sys.stderr.write(note.lstrip("\n") + "\n")
    elif cmd == "dims":
        d = load()
        for dim in DIMS:
            vals = sorted({e.get(dim, "") for e in secs(d) if e.get(dim)})
            print(f"{dim:12}: {', '.join(vals) or '-'}")
        colls = sorted({e.get("collection", "") for e in secs(d) if e.get("collection")})
        print(f"{'collection':12}: {', '.join(colls) or '-'}")
    elif cmd == "audit":
        if a and a[0] == "verify": print(audit_verify()); return
        if a and a[0] == "anchor":
            aa = a[1:]; persist = any(f in aa for f in ("--file", "--webhook", "--syslog"))
            file = _flag(aa, "--file"); webhook = _flag(aa, "--webhook")
            syslog = True if "--syslog" in aa else None
            rec, sent = anchor_push(file=file, webhook=webhook, syslog=syslog, persist=persist)
            if not rec: return print("audit log is still empty — no anchor.")
            print(f"anchor: seq={rec['seq']} hash={rec['hash'][:16]}…  sent: {','.join(sent) or '(no target)'}")
            if not sent: print("  hint: give a target → concealer audit anchor --file ~/anchors.log [--syslog] [--webhook URL]")
            return
        for r in audit_rows()[-40:]:
            who = f"[{r['actor']}] " if r.get("actor") else ""
            print(f"{r['ts']:20} {r['source']:6} {r['action']:10} {r['key']:24} {who}{r.get('detail','')}")
    elif cmd == "get":
        hits = filt(load(), _sel(a))
        if len(hits) != 1: sys.exit(f"{len(hits)} records matched, narrow it down.")
        e = hits[0]; actor = _cli_actor()
        allowed, note = rate_gate(actor, [e])   # reading a value also counts toward the distinct-name quota (blocks get-loops)
        if not allowed:
            audit("get_denied", key=e["name"], source="cli", detail=label(e), actor=actor)
            sys.exit(note.lstrip("\n") or "limit: access quota exhausted.")
        audit("get", key=e["name"], source="cli", detail=label(e), actor=actor)
        if e["type"] == "api_key": print(e["fields"].get("value", ""))
        else:
            for fn, fv in e["fields"].items(): print(f"{fn}={fv}")
    elif cmd in ("set", "add"):
        tags = _flag(a, "--tags"); coll = _flag(a, "--collection")
        rdays = _flag(a, "--rotate-days"); rmode = _flag(a, "--rotate-mode")
        sel = _sel(a); typ = sel.pop("type", "api_key")
        rot = None
        if rdays is not None:
            try: rot = {"every_days": max(0, int(rdays)), "mode": rmode or "generate", "last": now_iso()}
            except ValueError: sys.exit("--rotate-days must be a number")
        if "name" not in sel: sys.exit("--name required")
        if not a: sys.exit("value required (for api_key) or field=val pairs")
        d = load(); ident = {dim: sel.get(dim, "") for dim in DIMS}; ident["name"] = sel["name"]
        hit = next((e for e in live(d) if matches(e, ident)), None)   # a tombstone with the same name never blocks re-create
        fields = {}
        if "=" in a[0]:
            for kv in a:
                k, _, v = kv.partition("="); fields[k] = v
        else:
            fields = {"value": a[0]}
        fields, bad = _clean_fields(fields)   # reject fields with secret-like (leaked) names
        if bad: sys.exit("invalid field name (looks like a secret value): " + ", ".join(mask(b) for b in bad))
        if hit:
            hit["fields"].update(fields); hit["updated"] = now_iso()
            if tags is not None: hit["tags"] = [t for t in tags.split(",") if t]
            if coll is not None: hit["collection"] = coll.strip().strip("/")
            if rot is not None: hit["rotation"] = rot
            act = "update"
        else:
            e = dict(ident); e["type"] = typ; e["fields"] = fields
            e["tags"] = [t for t in (tags or "").split(",") if t]
            if coll is not None: e["collection"] = coll.strip().strip("/")
            if rot is not None: e["rotation"] = rot
            secs(d).append(norm(e)); act = "create"
        save(d); audit(act, key=sel["name"], source="cli", detail=label(ident))
        print(f"{act}: {sel['name']} @ {label(ident)}")
    elif cmd == "rotate":
        if "--due" in a:   # bulk: records past their policy due date (cron friendly). generate → new value, manual → warn only
            dry = "--dry" in a; d = load(); did = 0; flagged = 0
            for e in secs(d):
                over = rotation_overdue(e)
                if over is None: continue
                mode = (e.get("rotation") or {}).get("mode", "generate")
                if mode == "generate" and "value" in e.get("fields", {}):
                    if not dry:
                        e["fields"]["value"] = _secrets.token_urlsafe(32)
                        e["rotation"]["last"] = e["updated"] = now_iso()
                        audit("rotate", key=e["name"], source="cli", detail="auto")
                    did += 1; print(f"{'[dry] ' if dry else ''}rotate: {e['name']} @ {label(e)} ({over}d overdue)")
                else:   # manual or no 'value' field (multi-field credential) → warn without breaking the value
                    flagged += 1; print(f"WARN: {e['name']} @ {label(e)} ({over}d overdue) — rotate manually ({mode})")
            if did and not dry: save(d)
            return print(f"\n{did} rotated, {flagged} awaiting manual rotation." + (" (dry-run: nothing written)" if dry else ""))
        d = load(); hits = [e for e in secs(d) if matches(e, _sel(list(a)))]
        if len(hits) != 1: sys.exit(f"{len(hits)} records matched, narrow it down.")
        val = a[0] if a and not a[0].startswith("--") else _secrets.token_urlsafe(32)
        hits[0]["fields"]["value"] = val; hits[0]["updated"] = now_iso()
        if hits[0].get("rotation", {}).get("every_days"): hits[0]["rotation"]["last"] = hits[0]["updated"]  # reset the clock
        save(d)
        audit("rotate", key=hits[0]["name"], source="cli"); print(f"rotate: {hits[0]['name']} -> {mask(val)}")
    elif cmd == "rm":
        sel = _sel(a)   # evaluate once — _sel mutates `a`, so calling it inside the comprehension would empty the selector after the first row
        d = load(); hits = [e for e in live(d) if matches(e, sel)]
        if len(hits) != 1: sys.exit(f"{len(hits)} records matched, narrow it down.")
        tombstone(d, hits[0]); save(d)
        audit("delete", key=hits[0]["name"], source="cli"); print(f"rm: {hits[0]['name']}")
    elif cmd in ("mv", "cp"):   # move to collection (mv: update the field) / copy (cp: clone + new id)
        to = _flag(a, "--to-collection"); newname = _flag(a, "--as")
        if to is None: sys.exit("--to-collection required")
        to = to.strip().strip("/")
        d = load(); hits = [e for e in secs(d) if matches(e, _sel(list(a)))]
        if len(hits) != 1: sys.exit(f"{len(hits)} records matched, narrow it down.")
        e = hits[0]
        if cmd == "mv":
            e["collection"] = to; e["updated"] = now_iso(); save(d)
            audit("update", key=e["name"], source="cli", detail=f"collection={to or '-'}")
            print(f"mv: {e['name']} -> 📁{to or '(root)'}")
        else:
            ne = norm({k: (list(v) if isinstance(v, list) else dict(v) if isinstance(v, dict) else v)
                       for k, v in e.items() if k != "id"})   # deep-ish copy, drop id → norm generates a new id
            ne["collection"] = to
            if newname: ne["name"] = newname
            ne["created"] = ne["updated"] = now_iso()
            secs(d).append(ne); save(d)
            audit("create", key=ne["name"], source="cli", detail=f"cp collection={to or '-'}")
            print(f"cp: {e['name']} -> {ne['name']} @ 📁{to or '(root)'} (id {ne['id']})")
    elif cmd == "run":
        sel = _sel(a); names = [sel.pop("name")] if "name" in sel else None   # --name X → inject only X
        for dim in ("repo", "project"): sel.setdefault(dim, detect(dim))
        env, _, _ = inject_env(sel, source="cli", actor=_cli_actor(), command=" ".join(a), names=names)
        sys.stderr.write(f"[concealer] {label(sel)}\n")
        os.execvpe(a[0], a, env)
    elif cmd == "leaks":
        gs = leak_scan(); audit("leak_scan", source="cli")
        if not gs: print("no shared (reused) secret values."); return
        for g in gs:
            print(f"[{g['severity']:4}] score {g['score']:3}  x{g['count']}  {g['mask']:14}  "
                  f"projects={','.join(g['projects']) or '-'}  envs={','.join(g['envs']) or '-'}")
            for u in g["uses"]: print(f"        - {u['name']} @ {u['scope']} ({u['field']})")
    elif cmd == "history":
        purge = "--purge" in a
        hits = history_scan(); audit("history_scan", key=f"{len(hits)} hits", source="cli")
        if not hits: print("no secrets found in shell history."); return
        for h in hits:
            print(f"[{h['severity']:4}] {h['file']}:{h['line']:<5} {h['mask']:14} ({','.join(h['reasons'])})")
            print(f"        {h['cmd']}")
        if purge:
            n = history_purge(hits); audit("history_purge", key=f"{n} lines", source="cli")
            print(f"\nhistory cleaned: {n} lines deleted (backup: *.concealer.bak)")
            print("note: open shell sessions may rewrite the in-memory history — run 'history -c'.")
        else:
            print(f"\n{len(hits)} findings. to delete from history: concealer history --purge")
    elif cmd == "scan":
        scan_env = "--envvars" in a
        if not a or (a[0].startswith("--") and not scan_env):
            sys.exit("usage: concealer scan <folder> [--import] [--history] [--envvars] [--project P --env E ..]")
        root = "" if a[0].startswith("--") else a.pop(0)
        do_import = "--import" in a; history = "--history" in a
        a = [x for x in a if x not in ("--import", "--history", "--envvars")]
        sel = _sel(a); cands = scan_folder(root, history, scan_env)
        if not cands: print("no candidate secrets found."); return
        print(f"{len(cands)} candidates:")
        for c in cands: print(f"  {c['name']:28} {c['mask']:14} <- {c['source']}")
        if not do_import: print("\n(dry run) add --import to import them"); return
        with _vault_lock():
            d = load(); scope = {dim: sel.get(dim, "") for dim in DIMS}
            if not scope["project"] and root: scope["project"] = os.path.basename(os.path.abspath(os.path.expanduser(root)))
            n_new, n_skip = _import_cands(d, cands, scope); save(d)
        audit("scan_import", key=f"{n_new} secrets", source="scan", detail=root)
        print(f"\nimported: {n_new}, skipped (existing): {n_skip}  @ {label(scope)}")
    elif cmd == "policy":
        sub = a[0] if a else "list"
        if sub == "check":   # cron friendly: exit code 1 if there are violations
            ev = policy_eval(); tot = 0
            for p in ev:
                if not p.get("enabled", True) or not p["count"]: continue
                tot += p["count"]
                print(f"[{p['name']}] ({p['kind']}, {p['audience']}) — {p['count']} violation(s):")
                for v in p["violations"]: print(f"  - {v['name']} @ {v['scope']}: {v['reason']}")
            print(f"\n{tot} total violation(s).")
            if tot: sys.exit(1)
        else:   # list
            pols = CFG.get("policies") or []
            if not pols: return print("no policies. add them in the web UI (Policy tab).")
            for p in pols:
                print(f"{p['id']}  {p['name']:24} kind={p['kind']:9} audience={p['audience']:6} "
                      f"{'on' if p.get('enabled', True) else 'off'}{'  🔔' if p.get('notify') else ''}")
    elif cmd == "expose":
        offline = "--offline" in a; a = [x for x in a if x != "--offline"]
        sel = _sel(a) or None
        if not offline: print("checking online (HIBP k-anonymity: only a SHA-1 prefix leaves this machine)…")
        res = exposure_scan(sel=sel, online=not offline)
        audit("exposure_scan", key=f"{len(res)} checked", source="cli", detail="offline" if offline else "hibp-range")
        if not res: return print("no high-entropy secret values to check.")
        for r in res:
            pw = r["pwned"]
            tag = "NET-ERR" if pw == -1 else (f"PWNED x{pw}" if pw and pw > 0 else ("clean" if pw == 0 else "—"))
            print(f"[{r['severity']:4}] {r['name']:24} {r['field']:12} {r['mask']:14} {tag}")
            if r["validate"]: print(f"        ↳ {r['validate']}")
        bad = sum(1 for r in res if (r["pwned"] or 0) > 0)
        print(f"\n{len(res)} checked, {bad} found in known breaches. CWE-798 applies to any hard-coded credential.")
        if bad: sys.exit(2)
    elif cmd == "gitscan":
        if not a or a[0].startswith("--"): sys.exit("usage: concealer gitscan <repo>")
        repo = a[0]; res = git_scan(repo); logs = log_scan(repo)
        audit("git_scan", source="cli", detail=repo)
        if not res.get("git"): print("not a git repo (still scanning logs)…")
        for c in res.get("committed", []):
            print(f"COMMITTED  {c['mask']:14} in {len(c['commits'])} commit(s): " + ", ".join(x['hash'] for x in c['commits']))
        for t in res.get("tracked", []):
            print(f"TRACKED    {t['file']}:{t['line']}  {t['mask']}")
        for g in res.get("gitignore_gaps", []):
            print(f"NOT-IGNORED  {g}  (add to .gitignore)")
        for l in logs:
            print(f"LOG [{l['severity']:4}] {l['file']}:{l['line']}  {l['mask']}")
        tot = len(res.get("committed", [])) + len(res.get("tracked", [])) + len(logs)
        print(f"\n{tot} finding(s), {len(res.get('gitignore_gaps', []))} ignore gap(s).")
        if res.get("committed") or res.get("tracked"):
            print("history cleanup guide: run `concealer web` → Risks → Exposure → 'Show cleanup guide' "
                  "(concealer NEVER rewrites history for you).")
    elif cmd == "export":
        out = a[0] if a and not a[0].startswith("--") else f"concealer-export-{now_iso()[:10]}{CER_EXT}"
        pw = getpass.getpass("Master password (bundle encryption): ")
        if not verify_master(pw): sys.exit("wrong password.")
        blob = _cer_wrap(export_bundle(pw))   # same opaque .cerbak container as backups; import auto-detects
        open(out, "wb").write(blob)
        audit("export", source="cli", detail=out); print(f"export: {out} ({len(blob)} bytes)")
    elif cmd == "import":
        mode = "overwrite"; files = []
        for x in a:
            if x.startswith("--mode="): mode = x.split("=", 1)[1]
            else: files.append(x)
        if not files: sys.exit("usage: concealer import <bundle.cerbak> [--mode=overwrite|skip|duplicate]")
        if mode not in ("overwrite", "skip", "duplicate"): sys.exit("mode must be overwrite|skip|duplicate")
        pw = getpass.getpass("Bundle password: ")
        try: nn, nu, ns = import_bundle(pw, open(files[0], "rb").read(), mode)
        except Exception as ex: sys.exit(f"import error: {scrub(ex)}")
        audit("import", source="cli", detail=f"{files[0]} mode={mode}")
        print(f"import ({mode}): +{nn} new, ~{nu} updated, ={ns} skipped")
    elif cmd == "config":
        if not a:
            for k, v in CFG.items(): print(f"{k} = {v}")
        elif len(a) == 1: print(CFG.get(a[0]))
        else:
            k, v = a[0], a[1]
            CFG[k] = int(v) if k == "idle" else ([x for x in v.split(",") if x] if k == "confirm_ops" else v)
            _cfg_persist(); print(f"{k} = {CFG[k]}")   # keeps limits/policies (the old 2-key save dropped them)
    elif cmd == "deploy":
        target = _flag(a, "--target") or "dotenv"
        scope = _sel(a); scope.pop("name", None); scope.pop("type", None)
        out = deploy_render(scope, target)
        audit("deploy", source="cli", detail=f"{target} {label(scope)}")
        print(out or "(no match)")
    elif cmd == "web": _chrome_selfheal(); serve_web(int(a[0]) if a else 8787)
    elif cmd == "demo": demo_cmd(a)
    elif cmd == "_demo-seed": _demo_seed()   # internal: seed sample secrets into the demo vault
    elif cmd == "lan": serve_lan(int(a[0]) if a else 8788, int(a[1]) if len(a) > 1 else 8787)
    elif cmd == "service": service_cmd(a)
    elif cmd == "mcp": mcp_stdio()
    elif cmd in ("chrome-extension", "chrome-ext"): install_chrome_extension(a)
    else:
        print(HELP)

# ---------------- LAN bridge (phone access over the local network) ----------------
# `serve_web` binds 127.0.0.1 only and refuses non-loopback Host/Origin (anti-DNS-
# rebinding, see H._guard). That keeps a browser on THIS machine safe but blocks a
# phone. `serve_lan` puts a thin reverse proxy on the LAN: it accepts only clients
# on a private/link-local address, rewrites Host/Origin back to loopback, and forwards
# to a local web instance. The master password stays the only gate; no vault state or
# key lives in this process — it just relays bytes to the web server that holds them.
_LAN_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
            "te", "trailers", "transfer-encoding", "upgrade", "host", "origin"}

def _lan_is_private(ip):
    """True only for private/loopback/link-local peers — the 'same LAN only' gate."""
    import ipaddress
    try: a = ipaddress.ip_address(ip)
    except ValueError: return False
    return a.is_private or a.is_loopback or a.is_link_local

def _lan_backend_cmd():
    """Path to the web-serving instance to run as backend. Prefer an installed
    `concealer`/`cer` on PATH that ISN'T this checkout, so the LAN bridge opens the
    user's real (globally configured) vault rather than a repo-local one; fall back
    to this script only if no separate install is found."""
    real = os.path.realpath(__file__)
    for name in ("concealer", "cer"):
        p = shutil.which(name)
        try:
            if p and os.path.realpath(p) != real: return [p]
        except OSError: pass
    return [sys.executable, _stable_self()]

def serve_lan(lan_port, web_port):
    import socket, urllib.error
    backend = f"127.0.0.1:{web_port}"

    def _up():
        s = socket.socket(); s.settimeout(0.3)
        try: s.connect(("127.0.0.1", web_port)); return True
        except OSError: return False
        finally: s.close()

    def _start_backend():   # start the backend web instance if nothing is serving on the loopback port
        if _up(): return True
        env = dict(os.environ); env["CONCEALER_NO_OPEN"] = "1"; env.pop("CONCEALER_WEB_IDLE_EXIT", None)
        kw = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL, "env": env}
        if os.name == "nt": kw["creationflags"] = 0x00000008 | 0x00000200
        else: kw["start_new_session"] = True
        subprocess.Popen(_lan_backend_cmd() + ["web", str(web_port)], **kw)
        for _ in range(40):                       # wait up to ~6s for it to bind
            if _up(): return True
            time.sleep(0.15)
        return False
    if not _start_backend():
        sys.exit(scrub("could not start the web instance to bridge — run `concealer web` first"))
    # Keep http://127.0.0.1:<web_port> always answering while this (service) runs: an on-demand
    # server started by the Chrome extension idle-exits, so re-spawn it whenever it goes away.
    def _keepalive():
        while True:
            time.sleep(60)
            try: _start_backend()
            except Exception: pass
    threading.Thread(target=_keepalive, daemon=True).start()

    class LanProxy(http.server.BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"
        def _relay(self):
            if not _lan_is_private(self.client_address[0]):
                self.send_response(403); self.send_header("Content-Length", "0"); self.end_headers(); return
            n = int(self.headers.get("Content-Length") or 0)
            body = self.rfile.read(n) if n else None
            hdrs = {k: v for k, v in self.headers.items() if k.lower() not in _LAN_HOP}
            hdrs["Host"] = backend                          # satisfy the backend's loopback Host guard
            if self.headers.get("Origin"): hdrs["Origin"] = f"http://{backend}"
            req = urllib.request.Request(f"http://{backend}{self.path}", data=body,
                                         headers=hdrs, method=self.command)
            try:
                with urllib.request.urlopen(req, timeout=30) as r: self._send(r.status, r.headers, r.read())
            except urllib.error.HTTPError as e:              # pass 4xx/5xx (e.g. wrong password) through verbatim
                self._send(e.code, e.headers, e.read())
            except Exception:
                self.send_response(502); self.send_header("Content-Length", "0"); self.end_headers()
        def _send(self, code, hdrs, payload):
            self.send_response(code)
            for k, v in hdrs.items():
                if k.lower() in _LAN_HOP or k.lower() == "content-length": continue
                self.send_header(k, v)
            self.send_header("Content-Length", str(len(payload))); self.end_headers()
            try: self.wfile.write(payload)
            except (BrokenPipeError, ConnectionResetError): pass
        do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = _relay
        def log_message(self, *a): pass

    host = socket.gethostname().split(".")[0]
    srv = http.server.ThreadingHTTPServer(("0.0.0.0", lan_port), LanProxy)
    si = server_info()
    adv = _advertise_mdns(si.get("label", host), lan_port, si["id"])   # best-effort: phones auto-discover this vault
    if adv:
        import atexit, signal
        atexit.register(lambda: adv.terminate())                      # don't orphan the mDNS responder on exit/crash
        signal.signal(signal.SIGTERM, lambda *a: (adv.terminate(), sys.exit(0)))
    disc = "discoverable" if adv else "manual entry"
    print(f"concealer lan: http://{host}.local:{lan_port}  (same LAN only, {disc}, unlock with master pw, Ctrl+C to stop)")
    try: srv.serve_forever()
    except KeyboardInterrupt: pass
    finally:
        if adv:
            try: adv.terminate()
            except Exception: pass

def _advertise_mdns(label, port, vault_id):
    """Best-effort mDNS/Bonjour advertisement of _concealer._tcp via the OS responder (dns-sd on macOS/Windows,
    avahi-publish-service on Linux). TXT carries the stable vault id + label so a phone can pick THE vault by id,
    not by ip/port. Returns the Popen (kept alive for the server's lifetime) or None if no responder is present."""
    name = f"concealer ({label})"
    kw = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
    if os.name != "nt": kw["start_new_session"] = True
    try:
        if shutil.which("dns-sd"):
            return subprocess.Popen(["dns-sd", "-R", name, "_concealer._tcp", "local", str(port),
                                     f"id={vault_id}", f"label={label}"], **kw)
        if shutil.which("avahi-publish-service"):
            return subprocess.Popen(["avahi-publish-service", name, "_concealer._tcp", str(port),
                                     f"id={vault_id}", f"label={label}"], **kw)
    except Exception: pass
    return None

# ---------------- auto-start service (no manual `concealer lan`) ----------------
SERVICE_LABEL = "com.fxerkan.concealer.lan"

def _service_exe():
    """The concealer to run as the service — prefer an installed concealer/cer on PATH (the user's global vault),
    else this script. Mirrors _lan_backend_cmd so the service opens the real vault, not a repo checkout."""
    real = os.path.realpath(__file__)
    for name in ("concealer", "cer"):
        p = shutil.which(name)
        try:
            if p and os.path.realpath(p) != real: return [p]
        except OSError: pass
    return [sys.executable, _stable_self()]

def service_cmd(a):
    """install|uninstall|status — run `concealer lan` automatically as a per-user background service so phones
    can always reach the vault (and auto-discover it) without anyone running `concealer lan` by hand."""
    sub = (a[0].lower() if a else "status")
    exe = _service_exe()
    if sys.platform == "darwin": _service_launchd(sub, exe)
    elif sys.platform.startswith("linux"): _service_systemd(sub, exe)
    elif os.name == "nt": _service_windows(sub, exe)
    else: sys.exit("service auto-start isn't supported here; run `concealer lan` from your own init system.")

def _service_launchd(sub, exe):
    d = os.path.expanduser("~/Library/LaunchAgents"); plist = os.path.join(d, SERVICE_LABEL + ".plist")
    if sub in ("install", "start", "enable"):
        args = "".join(f"<string>{html.escape(x)}</string>" for x in exe + ["lan"])
        # launchd runs with a minimal PATH — embed the install-time PATH so sops/age/dns-sd are found
        envitems = [("PATH", os.environ.get("PATH") or "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")]
        if os.environ.get("CONCEALER_HOME"): envitems.append(("CONCEALER_HOME", HOME))
        env = "<key>EnvironmentVariables</key><dict>" + "".join(
            f"<key>{k}</key><string>{html.escape(v)}</string>" for k, v in envitems) + "</dict>"
        os.makedirs(d, exist_ok=True)
        open(plist, "w").write('<?xml version="1.0" encoding="UTF-8"?>\n'
            '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
            f'<plist version="1.0"><dict><key>Label</key><string>{SERVICE_LABEL}</string>'
            f'<key>ProgramArguments</key><array>{args}</array>'
            f'<key>RunAtLoad</key><true/><key>KeepAlive</key><true/>{env}</dict></plist>\n')
        os.chmod(plist, 0o644)
        subprocess.run(["launchctl", "unload", plist], capture_output=True)
        r = subprocess.run(["launchctl", "load", "-w", plist], capture_output=True, text=True)
        if r.returncode: sys.exit(scrub(r.stderr.strip() or "launchctl load failed"))
        print(f"service installed — `concealer lan` runs at login and auto-discovers this vault (launchd: {SERVICE_LABEL}).")
    elif sub in ("uninstall", "stop", "disable", "remove"):
        subprocess.run(["launchctl", "unload", "-w", plist], capture_output=True)
        try: os.remove(plist)
        except OSError: pass
        print("service removed.")
    else:
        on = SERVICE_LABEL in subprocess.run(["launchctl", "list"], capture_output=True, text=True).stdout
        print(f"service: {'running' if on else 'not installed'} (launchd: {SERVICE_LABEL})")

def _service_systemd(sub, exe):
    d = os.path.expanduser("~/.config/systemd/user"); unit = os.path.join(d, "concealer-lan.service")
    if sub in ("install", "start", "enable"):
        execstart = " ".join(shlex.quote(x) for x in exe + ["lan"])
        envline = f"Environment=PATH={os.environ.get('PATH') or '/usr/local/bin:/usr/bin:/bin'}\n"
        if os.environ.get("CONCEALER_HOME"): envline += f"Environment=CONCEALER_HOME={shlex.quote(HOME)}\n"
        os.makedirs(d, exist_ok=True)
        open(unit, "w").write("[Unit]\nDescription=concealer LAN bridge (device sync)\nAfter=network-online.target\n\n"
            f"[Service]\nExecStart={execstart}\n{envline}Restart=always\n\n[Install]\nWantedBy=default.target\n")
        subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
        r = subprocess.run(["systemctl", "--user", "enable", "--now", "concealer-lan"], capture_output=True, text=True)
        if r.returncode: sys.exit(scrub(r.stderr.strip() or "systemctl enable failed (need `loginctl enable-linger`?)"))
        print("service installed — `concealer lan` runs at login (systemd --user: concealer-lan).")
    elif sub in ("uninstall", "stop", "disable", "remove"):
        subprocess.run(["systemctl", "--user", "disable", "--now", "concealer-lan"], capture_output=True)
        try: os.remove(unit)
        except OSError: pass
        subprocess.run(["systemctl", "--user", "daemon-reload"], capture_output=True)
        print("service removed.")
    else:
        st = subprocess.run(["systemctl", "--user", "is-active", "concealer-lan"], capture_output=True, text=True).stdout.strip()
        print(f"service: {st or 'not installed'} (systemd --user: concealer-lan)")

def _service_windows(sub, exe):
    tn = "concealer-lan"; tr = " ".join(f'"{x}"' if " " in x else x for x in exe + ["lan"])
    if sub in ("install", "start", "enable"):
        r = subprocess.run(["schtasks", "/create", "/tn", tn, "/tr", tr, "/sc", "onlogon", "/rl", "limited", "/f"],
                           capture_output=True, text=True)
        if r.returncode: sys.exit(scrub(r.stderr.strip() or "schtasks create failed"))
        subprocess.run(["schtasks", "/run", "/tn", tn], capture_output=True)
        print(f"service installed — `concealer lan` runs at logon (Scheduled Task: {tn}).")
    elif sub in ("uninstall", "stop", "disable", "remove"):
        subprocess.run(["schtasks", "/delete", "/tn", tn, "/f"], capture_output=True)
        print("service removed.")
    else:
        ok = subprocess.run(["schtasks", "/query", "/tn", tn], capture_output=True).returncode == 0
        print(f"service: {'installed' if ok else 'not installed'} (Scheduled Task: {tn})")

# ---------------- Web (SPA + JSON API) ----------------
_SESSIONS = {}   # token -> last_activity_epoch
_SESS_KEY = {}   # token -> decrypted age key text (on a hardened vault; in memory, not written to disk)

# Brute-force throttle on /api/unlock: after UNLOCK_MAX consecutive wrong master passwords,
# lock the login for UNLOCK_COOLDOWN seconds. Keyed by client IP; in-memory only (resets on restart).
# ponytail: flat cooldown, single IP key — enough for a local single-user app. Upgrade path:
# exponential backoff or per-account escalation if this ever faces a real network attacker.
UNLOCK_MAX, UNLOCK_COOLDOWN = 5, 300
_UNLOCK_FAIL = {}   # ip -> [fail_count, locked_until_epoch]

def _unlock_locked_for(ip):
    """Seconds the given IP must wait before another unlock attempt (0 = not locked)."""
    st = _UNLOCK_FAIL.get(ip)
    if not st: return 0
    return max(0, int(st[1] - time.time()))
def _unlock_note(ip, ok):
    """Record an unlock outcome; on the UNLOCK_MAX-th consecutive failure, arm the cooldown."""
    if ok: _UNLOCK_FAIL.pop(ip, None); return
    st = _UNLOCK_FAIL.setdefault(ip, [0, 0.0]); st[0] += 1
    if st[0] >= UNLOCK_MAX: st[1] = time.time() + UNLOCK_COOLDOWN; st[0] = 0

def _lock_clear(tok=None):
    """Drop the in-memory key/session, then gc.collect() to reclaim freed copies.
    ponytail: BEST-EFFORT ONLY — CPython does not zeroize memory. Plaintext key/secret
    bytes may still linger in the process heap (and potentially swap or a core dump)
    until overwritten. This only shrinks the reachable-copy window; it is NOT secure
    erasure. See docs/security.md 'Known limitations: in-memory secrets'."""
    global _KEY_CACHE
    if tok is not None:
        _SESSIONS.pop(tok, None); _SESS_KEY.pop(tok, None)
    _KEY_CACHE = None
    if not _SESSIONS:                 # last session gone: drop pending autofill jobs + task grants
        _AF_JOBS.clear(); _AF_GRANTS.clear()
    gc.collect()

# ---------------- Secure Agentic Autofill (fill-without-reveal) ----------------
# An agent asks (over loopback) for a website/login secret to be typed into the page it is
# on. A human approves in the web UI; the concealer extension injects the value into the
# form. The value flows app -> extension -> DOM only — NEVER back to the agent/LLM. Job
# state lives in the WEB-SERVER process (the MCP process talks to it over 127.0.0.1). All
# memory-only, cleared on idle auto-lock like the session key.
_AF_JOBS = {}      # job_id -> {id,agent,domain,secret_id,secret_name,username,status,created,result,exposed}
_AF_GRANTS = {}    # "agent|domain|secret_id" -> {"exp":epoch,"max":int,"used":int} — "approve for this task"
_AF_TTL = 120      # seconds a pending/approved job stays live before it expires
AF_PORT = int(os.environ.get("CONCEALER_WEB_PORT", "8787"))   # loopback port the MCP tool reaches the web server on (extension default: 8787)

def _af_host(url):
    try: return (urllib.parse.urlparse(url if "://" in (url or "") else "//" + (url or ""), scheme="http").hostname or "").lower()
    except Exception: return ""

def registrable_domain(host):
    """Naive eTLD+1: the last two dot-labels. ponytail: no Public Suffix List, so
    multi-level TLDs (example.co.uk) collapse to 'co.uk'. Good enough here because the
    content script re-verifies the exact origin before filling; upgrade to a PSL if
    cross-subdomain phishing on odd TLDs becomes a concern."""
    parts = [p for p in (host or "").split(".") if p]
    return ".".join(parts[-2:]) if len(parts) >= 2 else host or ""

# Field aliases so ANY record type can drive a sign-in, not just website/login: a `custom`
# "AWS console" record with url/account_id/iam_user/console_password works the same way.
_AF_URL = ("web_url", "url", "console_url", "signin_url", "login_url")
_AF_USER = ("username", "user", "iam_user", "iam_username", "login", "email", "user_name")
_AF_PW = ("password", "pass", "console_password", "pwd")
_AF_ACCT = ("account_id", "aws_account_id", "account", "account_alias", "accountid")

def _af_first(f, keys):
    lo = {k.lower(): v for k, v in f.items() if isinstance(v, str) and v.strip()}
    return next((lo[k].strip() for k in keys if k in lo), "")

def af_login_view(e):
    """Normalise a record into {url, username, password, account}. account falls back to the
    12-digit id in an AWS-style URL (https://<id>.signin.aws.amazon.com/console)."""
    f = e.get("fields") or {}
    url = _af_first(f, _AF_URL) or (e.get("url") or "").strip()
    acct = _af_first(f, _AF_ACCT)
    if not acct:
        m = re.match(r"(\d{12})\.signin\.aws", _af_host(url)); acct = m.group(1) if m else ""
    return {"url": url, "username": _af_first(f, _AF_USER), "password": _af_first(f, _AF_PW), "account": acct}

# Sites that sign you in on another domain of the same company (SSO host != service URL), so a
# record saved as https://outlook.office.com still matches login.microsoftonline.com.
# ponytail: hand-kept table; extend when a real site needs it.
_AF_SAME = [{"microsoftonline.com", "office.com", "office365.com", "outlook.com", "live.com", "microsoft.com", "sharepoint.com"},
            {"openai.com", "chatgpt.com"}, {"google.com", "gmail.com"}, {"apple.com", "icloud.com"},
            {"proton.me", "protonvpn.com", "protonmail.com"}, {"amazon.com", "amazonaws.com"}]
def af_site(dom):
    return next((min(g) for g in _AF_SAME if dom in g), dom)

def _af_hint(target_url):
    """Account hint the PAGE carries: <id>.signin.aws.amazon.com or ?account=<id|alias>."""
    h = _af_host(target_url); m = re.match(r"([^.]+)\.signin\.aws", h)
    if m: return m.group(1)
    try: return (urllib.parse.parse_qs(urllib.parse.urlparse(target_url).query).get("account") or [""])[0]
    except Exception: return ""

def af_candidates(d, target_url, sel=None):
    """Records with a password whose URL shares the target's registrable domain, best first:
    account hint match > exact host match > name order."""
    host = _af_host(target_url); dom = registrable_domain(host); hint = _af_hint(target_url).lower()
    out = []
    for e in filt(d, sel):
        v = af_login_view(e)
        if not v["password"] or not dom or af_site(registrable_domain(_af_host(v["url"]))) != af_site(dom): continue
        rank = (0 if hint and v["account"].lower() == hint else 1, 0 if _af_host(v["url"]) == host else 1, e["name"].lower())
        out.append((rank, e, v))
    return [(e, v) for _, e, v in sorted(out, key=lambda x: x[0])]

def _af_pick_secret(d, target_url, name=None, sel=None):
    """Find a sign-in secret for this request. Returns (record|None, reason).
    reason: 'ok' | 'nomatch' | 'mismatch:<registrable-domain-of-secret>'."""
    dom = registrable_domain(_af_host(target_url))
    if name:
        e = next((x for x in filt(d, sel) if x["name"] == name and af_login_view(x)["password"]), None)
        if not e: return None, "nomatch"
        sdom = registrable_domain(_af_host(af_login_view(e)["url"]))
        if not sdom or af_site(sdom) != af_site(dom): return None, f"mismatch:{sdom or '?'}"   # no URL on the record = can't prove the origin
        return e, "ok"
    c = af_candidates(d, target_url, sel)
    return (c[0][0], "ok") if c else (None, "nomatch")

def _af_grant_k(agent, domain, sid): return f"{agent}|{domain}|{sid}"
def af_grant_mint(agent, domain, sid, ttl=900, max_uses=10):
    _AF_GRANTS[_af_grant_k(agent, domain, sid)] = {"exp": time.time() + ttl, "max": max_uses, "used": 0}
def af_grant_ok(agent, domain, sid):
    """True (and consumes one use) if a live task-grant covers this fill."""
    g = _AF_GRANTS.get(_af_grant_k(agent, domain, sid))
    if not g: return False
    if time.time() > g["exp"] or g["used"] >= g["max"]:
        _AF_GRANTS.pop(_af_grant_k(agent, domain, sid), None); return False
    g["used"] += 1; return True

def _af_expire():
    """Lazily mark stale pending/approved jobs expired (called on every read)."""
    now = time.time()
    for j in _AF_JOBS.values():
        if j["status"] in ("pending", "approved") and now - j["created"] > _AF_TTL:
            j["status"] = "expired"

def _af_local(method, path, tok, body=None):
    """Call the running web server over loopback (used by the MCP process to reach the job queue)."""
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(f"http://127.0.0.1:{AF_PORT}{path}", data=data, method=method,
        headers={"X-Concealer-Token": tok, "Content-Type": "application/json", "Host": f"127.0.0.1:{AF_PORT}"})
    with urllib.request.urlopen(req, timeout=5) as resp:
        return json.loads(resp.read() or "{}")

def _af_new_job(agent, target_url, name):
    """Create a PENDING job from agent-supplied data only — NO vault access, so this works
    while the vault is locked. Secret matching happens later in _af_resolve() once unlocked."""
    jid = _secrets.token_urlsafe(9)
    _AF_JOBS[jid] = {"id": jid, "agent": agent, "target_url": target_url,
                     "domain": registrable_domain(_af_host(target_url)), "name": name or "",
                     "status": "pending", "created": time.time(), "result": "", "exposed": False,
                     "secret_id": "", "secret_name": "", "username": "", "match": ""}
    return _AF_JOBS[jid]

def _af_resolve(job, d):
    """Match a pending job to a secret using the UNLOCKED vault data. Idempotent.
    Sets secret_id/secret_name/username/match; returns match: 'ok'|'nomatch'|'mismatch:<dom>'."""
    e, reason = _af_pick_secret(d, job["target_url"], job["name"] or None)
    job["match"] = reason
    job["secret_id"] = e["id"] if e else ""
    job["secret_name"] = e["name"] if e else ""
    job["username"] = af_login_view(e)["username"] if e else ""
    return reason

# ---------------- demo mode: a throwaway vault with sample data (mirrors the mobile "Try the demo") ----
# Same sample set as mobile/www (index.html demoSecrets). All values are dummy (DEMO/test only).
_DEMO_SECRETS = [
    {"name": "OpenAI API Key", "type": "api_key", "project": "demo", "repo": "demo", "environment": "prod",
     "tags": ["ai", "demo"], "fields": {"value": "sk-DEMO-openai-3f9a2b7c4d5e6f7a8b9c0d1e"}},
    {"name": "GitHub Token", "type": "access_token", "project": "demo", "repo": "demo", "environment": "prod",
     "tags": ["git", "demo"], "fields": {"token": "ghp_DEMO1234abcd5678efgh9012ijkl3456mnop", "refresh_token": "",
                                          "scopes": "repo, read:org", "expires": "2027-01-01"}},
    {"name": "App Database", "type": "database", "project": "demo", "repo": "demo", "environment": "prod",
     "tags": ["db", "demo"], "fields": {"host": "db.demo.local", "port": "5432", "database": "appdb", "schema": "public",
                                         "username": "app", "password": "DEMO-pg-pw-9f8e7d", "auth_type": "password",
                                         "jdbc_url": "jdbc:postgresql://app:DEMO-pg-pw-9f8e7d@db.demo.local:5432/appdb"}},
    {"name": "AWS Access", "type": "custom", "project": "demo", "repo": "demo", "environment": "prod",
     "tags": ["cloud", "demo"], "field_meta": {"secret_access_key": {"secret": True}},
     "fields": {"access_key_id": "AKIADEMO1234567890", "secret_access_key": "DEMO/secretExampleKeyDoNotUse1234567890",
                "region": "eu-central-1"}},
    {"name": "Stripe (test)", "type": "api_key", "project": "demo", "repo": "demo", "environment": "prod",
     "tags": ["payments", "demo"], "fields": {"value": "sk_test_DEMO_51ExampleKeyDoNotUse1234"}},
    {"name": "Email Login", "type": "login", "project": "demo", "repo": "demo", "environment": "prod",
     "tags": ["demo"], "fields": {"web_url": "https://mail.demo.example", "username": "demo@example.com",
                                   "password": "DEMO-mail-pw-2b3c", "totp": "DEMOTOTPSEED234567"}},
]

def _demo_seed():
    """Append the sample secrets to the (already-unlocked, via CONCEALER_TOKEN) demo vault."""
    d = load(); have = {s.get("name") for s in d["secrets"]}; n = 0
    for rec in _DEMO_SECRETS:
        if rec["name"] in have: continue
        e = dict(rec); e.setdefault("tenant", "*"); norm(e); d["secrets"].append(e); n += 1
    if n: save(d)
    print(f"seeded {n} demo secret(s)")

def demo_cmd(a):
    """`concealer demo [port]` — create/serve a throwaway demo vault with sample data. The real
    vault is never touched: it lives in a temp dir and can be deleted any time. Master pw: demo1234."""
    import re as _re
    port = int(a[0]) if a and a[0].isdigit() else 8799
    home = os.path.join(tempfile.gettempdir(), "concealer-demo")
    script = os.path.realpath(__file__); py = sys.executable
    env = {**os.environ, "CONCEALER_HOME": home}
    if not os.path.exists(os.path.join(home, "secrets.enc.yaml")):
        os.makedirs(home, exist_ok=True)
        print("Creating a throwaway demo vault with sample data…")
        r = subprocess.run([py, script, "init"], input="demo1234\ndemo1234\n", text=True, capture_output=True, env=env)
        if r.returncode: sys.exit("demo setup failed:\n" + scrub(r.stderr))
        m = _re.search(r"CONCEALER_TOKEN=([^\s\x1b]+)", r.stdout)
        s = subprocess.run([py, script, "_demo-seed"], text=True, capture_output=True,
                           env={**env, "CONCEALER_TOKEN": m.group(1) if m else ""})
        if s.returncode: sys.exit("demo seed failed:\n" + scrub(s.stderr))
    print(f"\n  concealer DEMO — throwaway vault with sample data (your real vault is untouched)."
          f"\n  Open:             http://127.0.0.1:{port}"
          f"\n  Master password:  demo1234"
          f"\n  Vault dir:        {home}   (safe to delete)\n")
    try: subprocess.run([py, script, "web", str(port)], env={**env, "CONCEALER_DEMO": "1"})
    except KeyboardInterrupt: pass

def serve_web(port):
    import time, threading
    _last = [time.time()]   # wall-clock of the last handled request (idle self-exit watchdog)
    def valid(tok):
        global _KEY_CACHE
        t = _SESSIONS.get(tok)
        if not t: return False
        if time.time() - t > CFG["idle"]:   # idle auto-lock: drop session + in-memory key, then gc
            _lock_clear(tok); return False
        _KEY_CACHE = _SESS_KEY.get(tok)     # cache the key for this request (sops reads from memory)
        return True   # fixed lifetime: activity does not extend the TTL (hard auto-lock)
    def remaining(tok):
        t = _SESSIONS.get(tok)
        return max(0, int(CFG["idle"] - (time.time() - t))) if t else 0

    class H(http.server.BaseHTTPRequestHandler):
        server_version = "concealer"
        def log_message(self, *a): pass
        def handle(self):
            _last[0] = time.time()
            try: super().handle()
            except (BrokenPipeError, ConnectionResetError): pass
        def end_headers(self):
            # Security response headers on EVERY reply (F2/F3). connect-src 'self' means even if
            # markup injection ran, it could not exfiltrate to a remote origin; frame-ancestors/
            # X-Frame-Options block clickjacking; nosniff blocks MIME confusion; no-store keeps
            # revealed secret JSON out of the browser disk cache. script/style 'unsafe-inline' is
            # still required by the inline handlers/styles in webui.html — remove it once those are
            # refactored to addEventListener + external CSS (upgrade path, see SECURITY_AUDIT_OWASP.md).
            self.send_header("Content-Security-Policy",
                             "default-src 'none'; script-src 'self' 'unsafe-inline'; "
                             "style-src 'self' 'unsafe-inline'; img-src 'self' data:; "
                             "connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
            self.send_header("X-Content-Type-Options", "nosniff")
            self.send_header("X-Frame-Options", "DENY")
            self.send_header("Referrer-Policy", "no-referrer")
            self.send_header("Cache-Control", "no-store")
            super().end_headers()
        def _guard(self):
            # Anti-DNS-rebinding (F4): the loopback bind only helps if the browser actually reached
            # us as 127.0.0.1/localhost. A rebinding page arrives with Host: evil.com — reject it.
            # Cross-origin state change is also refused unless the Origin is loopback or the extension.
            port = self.server.server_address[1]
            host = (self.headers.get("Host") or "").rsplit(":", 1)[0].strip().strip("[]").lower()
            # concealer.localhost: browsers resolve *.localhost to loopback themselves (never via DNS),
            # so it can't be rebound — a memorable name for the UI.
            if host and host not in ("127.0.0.1", "localhost", "::1", "concealer.localhost"):
                self._json({"error": "forbidden host"}, 403); return False
            origin = self.headers.get("Origin")
            if origin and not (origin.startswith("chrome-extension://")
                               or origin in (f"http://127.0.0.1:{port}", f"http://localhost:{port}", f"http://concealer.localhost:{port}")):
                self._json({"error": "forbidden origin"}, 403); return False
            return True
        def _af_agent(self):
            # Autofill request/status are reachable by a REGISTERED AGENT token (no human
            # session) — the agent may only ASK; approval + value delivery stay session-gated.
            e = _find_token(self._tok() or "")
            return e["label"] if e and e.get("source") == "agent" else None
        def _tok(self):
            # Header first: the Chrome extension is a cross-origin client, so the SPA's
            # HttpOnly SameSite=Strict cookie never rides along on its fetches. It holds
            # the token itself and sends it back here. The web SPA keeps using the cookie.
            h = self.headers.get("X-Concealer-Token")
            if h: return h
            c = self.headers.get("Cookie", "")
            for part in c.split(";"):
                if part.strip().startswith("tok="): return part.strip()[4:]
            return None
        def _json(self, obj, code=200, cookie=None):
            b = json.dumps(obj).encode()
            self.send_response(code); self.send_header("Content-Type", "application/json")
            if cookie: self.send_header("Set-Cookie", cookie)
            self.end_headers(); self.wfile.write(b)
        def _body(self):
            ln = int(self.headers.get("Content-Length", 0))
            return json.loads(self.rfile.read(ln) or "{}")

        def do_GET(self):
            if not self._guard(): return
            u = urllib.parse.urlparse(self.path); path = u.path
            q = {k: v[0] for k, v in urllib.parse.parse_qs(u.query).items()}
            if path == "/" or path == "/index.html":
                page = _read_webui()
                if page is None:
                    page = (b"<h1 style='font:600 20px system-ui;margin:2em'>The app was updated in place.</h1>"
                            b"<p style='font:15px system-ui;margin:0 2em'>This server is running from an old, "
                            b"removed install. Quit it and run <code>cer web</code> again.</p>")
                else:
                    page = page.replace(b"__IDLE__", str(CFG["idle"]).encode()).replace(b"__VERSION__", VERSION.encode()).replace(b"__DEMO__", b"1" if os.environ.get("CONCEALER_DEMO") else b"0")
                self.send_response(200); self.send_header("Content-Type", "text/html; charset=utf-8")
                self.end_headers(); self.wfile.write(page); return
            if path == "/api/session":
                tok = self._tok(); up = bool(tok and valid(tok))
                return self._json({"unlocked": up, "idle": CFG["idle"], "remaining": remaining(tok or ""), "version": VERSION})
            if path == "/api/serverinfo":          # unauthenticated identity for device discovery — id/label/version only, NO secret
                si = server_info()
                return self._json({"ok": True, "id": si["id"], "name": si.get("label", ""), "version": VERSION})
            if path == "/api/types":
                return self._json({t: [{"name": f, "secret": k == "secret"} for f, k in fs] for t, fs in TYPES.items()})
            if path == "/api/autofill/status":     # agent polls its own job (status string only, never a value)
                ag = self._af_agent()
                if not ag: return self._json({"error": "agent token required"}, 403)
                _af_expire(); j = _AF_JOBS.get(q.get("job", ""))
                if not j or j["agent"] != ag: return self._json({"status": "expired"})
                return self._json({"status": j["status"], "result": j["result"]})
            if path == "/api/autofill/notify":     # LOCKED-SAFE: count + opaque ids only, NO vault data.
                # Lets the extension badge + notify even while locked. With ?wait=<ids> it long-polls
                # (hangs up to ~25s until the pending-id set changes), so the badge updates near-instantly
                # and the MV3 worker stays awake — instead of a ~30s alarm clamp. Threaded server, so a
                # hanging GET only occupies its own handler thread.
                def _pend_ids(): _af_expire(); return sorted(j["id"] for j in _AF_JOBS.values() if j["status"] == "pending")
                if q.get("poll"):   # explicit flag: 'wait' alone is dropped by parse_qs when empty
                    seen = set(x for x in q.get("wait", "").split(",") if x); end = time.time() + 25
                    while time.time() < end:
                        ids = _pend_ids()
                        if set(ids) != seen: return self._json({"count": len(ids), "ids": ids})
                        time.sleep(0.5)
                ids = _pend_ids()
                return self._json({"count": len(ids), "ids": ids})
            if not valid(self._tok() or ""): return self._json({"error": "locked"}, 401)
            if path == "/api/autofill/pending":    # approval UI (session): resolve each pending job now that we're unlocked
                _af_expire(); d = load(); out = []
                for j in _AF_JOBS.values():
                    if j["status"] != "pending": continue
                    _af_resolve(j, d)
                    out.append({"id": j["id"], "agent": j["agent"], "domain": j["domain"],
                                "secret_name": j["secret_name"], "username": j["username"], "match": j["match"]})
                return self._json(out)
            if path == "/api/autofill/match":      # on-page suggestions for the human (session): names + usernames, NO secret values
                return self._json([{"id": e["id"], "name": e["name"], "username": v["username"], "account": v["account"], "scope": label(e)}
                                   for e, v in af_candidates(load(), q.get("url", ""))[:8]])
            if path == "/api/autofill/jobs":       # extension SW polls approved jobs (no values here)
                _af_expire()
                return self._json([{"id": j["id"], "domain": j["domain"], "secret_name": j["secret_name"]}
                                   for j in _AF_JOBS.values() if j["status"] == "approved"])
            if path == "/api/secrets":
                d = load(); sel = {dim: q[dim] for dim in DIMS if q.get(dim)}
                rows = filt(d, sel, q.get("tag"), q.get("q"), q.get("type"), q.get("collection"))
                acc = last_access()
                out = []
                for e in rows:
                    pe = entry_public(e); pe["access"] = acc.get(e["name"]); out.append(pe)
                return self._json(out)
            if path.startswith("/api/secret/"):
                sid = path.rsplit("/", 1)[-1]; d = load(); e = by_id(d, sid)
                if not e or e.get("deleted"): return self._json({"error": "not found"}, 404)
                reveal = q.get("reveal") == "1"
                if reveal:
                    audit("reveal", key=e["name"], source="web", detail=q.get("intent", "view"))
                return self._json(entry_public(e, reveal))
            if path == "/api/audit":
                rows = list(reversed(audit_rows()))
                for f in ("action", "source", "key"):
                    if q.get(f): rows = [r for r in rows if q[f].lower() in str(r.get(f, "")).lower()]
                if q.get("from"): rows = [r for r in rows if r["ts"] >= q["from"]]
                if q.get("to"): rows = [r for r in rows if r["ts"] <= q["to"]]
                page = int(q.get("page", 1)); size = int(q.get("size", 25))
                total = len(rows); s = (page - 1) * size
                return self._json({"rows": rows[s:s + size], "total": total, "page": page,
                                   "pages": max(1, (total + size - 1) // size)})
            if path == "/api/settings":
                return self._json({"idle": CFG["idle"], "confirm_ops": CFG["confirm_ops"],
                                   "limits": CFG.get("limits") or {"default": dict(_DEFAULT_LIMITS), "agents": {}},
                                   "agents": _agent_labels(), "hardened": not os.path.exists(KEY),
                                   "hibp_key_set": bool(_hibp_key())})   # the key ITSELF is not returned
            if path == "/api/backup":      # auto-backup status (password NOT returned)
                c = _backup_cfg()
                return self._json({"enabled": c["enabled"], "interval_h": c["interval_h"], "dir": c["dir"],
                                   "keep": c["keep"], "last": c["last"], "has_pw": bool(c.get("pw_wrapped"))})
            if path == "/api/leaks":
                audit("leak_scan", source="web"); return self._json(leak_scan())
            if path == "/api/health":
                audit("health_scan", source="web"); return self._json(health_scan())
            if path == "/api/policies":
                return self._json({"policies": policy_eval(), "kinds": list(_POLICY_KINDS), "audiences": list(_POLICY_AUD)})
            if path == "/api/history":
                hits = history_scan(); audit("history_scan", key=f"{len(hits)} hits", source="web")
                return self._json(hits)
            if path == "/api/browse":      # server-side folder browser for scan-folder (local app)
                raw = q.get("path") or os.path.expanduser("~")
                p = os.path.abspath(os.path.expanduser(raw))
                if not os.path.isdir(p): p = os.path.expanduser("~")
                try: dirs = sorted((n for n in os.listdir(p) if not n.startswith(".") and os.path.isdir(os.path.join(p, n))), key=str.lower)
                except Exception: dirs = []
                parent = os.path.dirname(p)
                return self._json({"path": p, "parent": parent if parent != p else None, "dirs": dirs})
            if path == "/api/pickdir":     # OS-native folder picker dialog (Finder/Explorer)
                sup = sys.platform == "darwin" or sys.platform.startswith("win") or bool(shutil.which("zenity") or shutil.which("kdialog"))
                return self._json({"path": _native_pickdir() if sup else None, "supported": sup})
            if path == "/api/audit/verify": return self._json(audit_verify())
            if path == "/api/audit/export":
                rows = audit_rows()
                if q.get("format") == "csv":
                    buf = io.StringIO(); w = csv.writer(buf)
                    w.writerow(["ts", "source", "action", "key", "detail", "hash"])
                    for r in rows: w.writerow([r["ts"], r["source"], r["action"], r["key"], r.get("detail", ""), r["hash"]])
                    data = buf.getvalue().encode(); ct = "text/csv"; fn = "audit.csv"
                else:
                    data = json.dumps(rows, indent=2).encode(); ct = "application/json"; fn = "audit.json"
                self.send_response(200); self.send_header("Content-Type", ct)
                self.send_header("Content-Disposition", f"attachment; filename={fn}")
                self.end_headers(); self.wfile.write(data); return
            self._json({"error": "not found"}, 404)

        def do_POST(self):
            global _KEY_CACHE
            if not self._guard(): return
            path = urllib.parse.urlparse(self.path).path
            if path == "/api/shutdown":
                # Let the on-demand launcher (Chrome native host) replace a server left over
                # from a previous install after an upgrade. No token needed — it only stops the
                # process (keys are already in memory only). Refuse browser callers (they send an
                # http(s) Origin); the native host uses urllib and sends none.
                if (self.headers.get("Origin") or "").startswith("http"):
                    return self._json({"error": "forbidden"}, 403)
                self._json({"ok": True}); self.wfile.flush()
                threading.Thread(target=lambda: (time.sleep(0.2), os._exit(0)), daemon=True).start()
                return
            if path == "/api/unlock":
                ip = self.client_address[0] if self.client_address else "?"
                wait = _unlock_locked_for(ip)
                if wait:                               # brute-force cooldown active → refuse without checking pw
                    audit("unlock_blocked", source="web")
                    return self._json({"ok": False, "locked": True, "retry_after": wait}, 429)
                pw = self._body().get("pw", "")
                keytext = key_from_master(pw)          # decrypt both verifies and yields the key
                if keytext or verify_master(pw):       # 2nd condition: legacy (plaintext-key) vault
                    _unlock_note(ip, True)
                    tok = _secrets.token_urlsafe(18); _SESSIONS[tok] = time.time()
                    if keytext: _SESS_KEY[tok] = keytext; _KEY_CACHE = keytext   # hardened: bind the key to the session in memory
                    audit("unlock", source="web")
                    _auto_backup_maybe()                   # if the interval elapsed, write a .cer at unlock (key in memory)
                    body = {"ok": True}
                    # Extension client can't read the HttpOnly cookie cross-origin; hand it the
                    # token in the body so it can send X-Concealer-Token. The SPA never sets this
                    # header, so its response body stays {ok:true} and the token stays HttpOnly for it.
                    if self.headers.get("X-Concealer-Client") == "ext": body["tok"] = tok
                    return self._json(body, cookie=f"tok={tok}; HttpOnly; Path=/; SameSite=Strict")
                _unlock_note(ip, False); audit("unlock_fail", source="web")
                wait = _unlock_locked_for(ip)
                if wait: return self._json({"ok": False, "locked": True, "retry_after": wait}, 429)
                return self._json({"ok": False}, 403)
            tok = self._tok()
            if path == "/api/lock":
                if tok:
                    _lock_clear(tok); audit("lock", source="web")
                return self._json({"ok": True})
            if path == "/api/sync":        # device sync: master-pw authenticated + self-unlocking (stateless — no prior web unlock needed).
                b = self._body()           # peer sends its age -p bundle (incl tombstones); gets the merged full set back.
                if not verify_master(b.get("pw", "")):
                    audit("sync_fail", source="web"); return self._json({"error": "bad_pw"}, 403)
                if not _KEY_CACHE:         # self-unlock the vault key from the master pw so a headless host needs no prior web unlock
                    kt = key_from_master(b.get("pw", ""))
                    if kt: _KEY_CACHE = kt
                try: blob = base64.b64decode(b.get("b64", ""))
                except Exception: return self._json({"error": "corrupt"}, 400)
                try: applied, out = sync_bundle(b.get("pw", ""), blob)
                except Exception as ex: return self._json({"error": scrub(ex)}, 400)
                audit("sync", source="web", detail=f"applied={applied}")
                return self._json({"ok": True, "applied": applied, "b64": base64.b64encode(out).decode()})
            if path == "/api/autofill/request":    # AGENT-authed: the agent may only ASK for a fill
                ag = self._af_agent()
                if not ag: return self._json({"error": "agent token required"}, 403)
                b = self._body(); target = b.get("target_url", "")
                j = _af_new_job(ag, target, b.get("name")); dom = j["domain"]
                # If the vault is already unlocked, resolve now so the agent gets fast nomatch/
                # mismatch feedback and a live task-grant can auto-approve. If LOCKED, the job
                # stays pending and the extension still alerts (locked-safe /notify) — the user
                # unlocks to review. The request itself never needs the vault to be open.
                if _SESSIONS:
                    try: reason = _af_resolve(j, load())
                    except Exception: reason = ""
                    if reason == "nomatch":
                        j["status"] = "denied"
                        audit("web_autofill_request", key=b.get("name", "") or dom, source="mcp", detail=f"{dom} nomatch", actor=ag)
                        return self._json({"status": "no matching secret"})
                    if reason.startswith("mismatch:"):
                        j["status"] = "denied"
                        audit("web_autofill_deny", key=b.get("name", ""), source="mcp", detail=f"domain mismatch {dom}!={reason[9:]}", actor=ag)
                        return self._json({"status": f"domain mismatch: secret is for {reason[9:]}"})
                    if af_grant_ok(ag, dom, j["secret_id"]):
                        j["status"] = "approved"   # a live task-grant covers it — no re-prompt
                        audit("web_autofill_request", key=j["secret_name"], source="mcp", detail=f"{dom} auto-granted", actor=ag)
                        return self._json({"job": j["id"], "status": "approved"})
                audit("web_autofill_request", key=j["name"] or dom, source="mcp", detail=dom, actor=ag)
                return self._json({"job": j["id"], "status": "pending"})
            if not valid(tok or ""): return self._json({"error": "locked"}, 401)
            if path == "/api/autofill/approve":    # human approves a pending fill (web UI or extension popup)
                b = self._body(); j = _AF_JOBS.get(b.get("job", ""))
                if not j or j["status"] != "pending": return self._json({"error": "gone"}, 404)
                reason = _af_resolve(j, load())    # (re)match now; anti-phishing enforced at approval time
                if reason != "ok":
                    j["status"] = "denied"
                    audit("web_autofill_deny", key=j["secret_name"] or j["name"], source="web", detail=f'{j["domain"]} {reason}')
                    return self._json({"error": "no matching secret" if reason == "nomatch" else "domain mismatch", "reason": reason}, 409)
                j["status"] = "approved"
                task = b.get("scope") == "task"
                if task: af_grant_mint(j["agent"], j["domain"], j["secret_id"])
                audit("web_autofill_approve", key=j["secret_name"], source="web", detail=j["domain"] + (" task" if task else ""))
                return self._json({"ok": True})
            if path == "/api/autofill/deny":
                b = self._body(); j = _AF_JOBS.get(b.get("job", ""))
                if not j: return self._json({"error": "gone"}, 404)
                j["status"] = "denied"
                audit("web_autofill_deny", key=j["secret_name"] or j["name"] or j["domain"], source="web", detail=j["domain"])
                return self._json({"ok": True})
            if path == "/api/autofill/fill":       # human clicked a suggestion on the page -> VALUE DELIVERY (session holds the key).
                # url is the tab URL as Chrome reports it to the extension (not page-supplied); the
                # record must belong to that registrable domain, and the content script re-checks origin.
                b = self._body(); d = load(); e = by_id(d, b.get("id", ""))
                ok = e and not e.get("deleted") and any(x["id"] == e["id"] for x, _ in af_candidates(d, b.get("url", "")))
                if not ok: return self._json({"error": "domain mismatch"}, 409)
                v = af_login_view(e); dom = registrable_domain(_af_host(b.get("url", "")))
                audit("web_autofill_fill", key=e["name"], source="ext", detail=dom + " manual")
                return self._json({"domain": dom, "username": v["username"], "password": v["password"], "account": v["account"]})
            if path == "/api/autofill/claim":      # extension SW claims an approved job -> VALUE DELIVERY (session holds the key)
                b = self._body(); j = _AF_JOBS.get(b.get("job", ""))
                if not j or j["status"] != "approved": return self._json({"error": "gone"}, 404)
                d = load(); e = by_id(d, j["secret_id"])
                if not e: j["status"] = "expired"; return self._json({"error": "gone"}, 404)
                j["status"] = "filling"
                v = af_login_view(e)
                return self._json({"domain": j["domain"], "username": v["username"], "password": v["password"], "account": v["account"]})
            if path == "/api/autofill/result":     # extension reports the fill outcome + post-fill exposure scan
                b = self._body(); j = _AF_JOBS.get(b.get("job", ""))
                if not j: return self._json({"error": "gone"}, 404)
                j["exposed"] = bool(b.get("exposed")); j["result"] = str(b.get("detail", ""))[:200]
                j["status"] = "done" if b.get("ok") else "failed"
                audit("web_autofill_fill", key=j["secret_name"], source="web", detail=f'{j["domain"]} {"ok" if b.get("ok") else "fail"}')
                if j["exposed"]: audit("web_autofill_exposed", key=j["secret_name"], source="web", detail=j["domain"])
                return self._json({"ok": True})
            if path == "/api/secrets":     # create
                with _vault_lock():
                    b = self._body(); d = load(); e = norm(_entry_from_body(b))
                    secs(d).append(e); save(d)
                audit("create", key=e["name"], source="web", detail=label(e))
                return self._json({"ok": True, "id": e["id"]})
            if path == "/api/copy":        # clipboard copy (audit)
                b = self._body(); audit("copy", key=b.get("key", ""), source="web", detail=b.get("field", ""))
                return self._json({"ok": True})
            if path == "/api/scan":        # dry scan (returns no value, masked)
                b = self._body(); cands = scan_folder(b.get("path", ""), b.get("history", False), b.get("env", False))
                audit("scan", source="web", detail=b.get("path", "") or ("env" if b.get("env") else ""))
                return self._json({"cands": [{"name": c["name"], "mask": c["mask"], "source": c["source"]} for c in cands]})
            if path == "/api/policies":    # create/update (session is enough; doesn't reveal a value)
                b = self._body(); pol = policy_upsert(b)
                audit("policy_set", key=pol["name"], source="web", detail=pol["kind"])
                return self._json({"ok": True, "policy": pol})
            if path == "/api/exposure":    # online leak check (HIBP k-anonymity; FULL VALUE DOESN'T LEAVE)
                b = self._body(); names = b.get("names"); ids = b.get("ids"); sel = b.get("sel") or None
                res = exposure_scan(ids=ids if isinstance(ids, list) else None,
                                    names=names if isinstance(names, list) else None, sel=sel, online=b.get("online", True))
                audit("exposure_scan", key=f"{len(res)} checked", source="web", detail="hibp-range")
                return self._json({"results": res})
            if path == "/api/breach":      # email breach query (HIBP; only the email is sent)
                b = self._body(); res = hibp_breaches(b.get("email", ""))
                audit("breach_check", key=b.get("email", ""), source="web")
                return self._json(res)
            if path == "/api/gitscan":     # git history + tracked files + log + gitignore (LOCAL)
                b = self._body(); root = b.get("path", "")
                res = git_scan(root); res["logs"] = log_scan(root)
                audit("git_scan", source="web", detail=root)
                return self._json(res)
            if path == "/api/gitremedy":   # remediation GUIDE text (NEVER executed)
                b = self._body()
                return self._json({"text": git_remediation(b.get("path", ""), b.get("files"), b.get("names"))})
            if path == "/api/settings":    # verify_master required (sensitive)
                b = self._body()
                if not verify_master(b.get("pw", "")):
                    audit("settings_fail", source="web"); return self._json({"error": "bad_pw"}, 403)
                if "idle" in b:
                    try: CFG["idle"] = max(30, min(86400, int(b["idle"])))
                    except Exception: pass
                if isinstance(b.get("confirm_ops"), list):
                    CFG["confirm_ops"] = [x for x in b["confirm_ops"] if x in ("export", "delete", "settings", "create", "update")]
                if isinstance(b.get("limits"), dict):
                    cur = CFG.get("limits") or {"default": dict(_DEFAULT_LIMITS), "agents": {}}
                    if isinstance(b["limits"].get("default"), dict):
                        cur["default"] = {**dict(_DEFAULT_LIMITS), **_clean_limit(b["limits"]["default"])}
                    if isinstance(b["limits"].get("agents"), dict):
                        cur["agents"] = {k: _clean_limit(v) for k, v in b["limits"]["agents"].items()
                                         if k and isinstance(v, dict) and _clean_limit(v)}
                    CFG["limits"] = cur
                if "hibp_key" in b:   # HIBP API key (user's own); empty string = clear
                    CFG["hibp_key"] = str(b["hibp_key"]).strip()
                _cfg_persist()
                audit("settings", source="web", detail=f"idle={CFG['idle']}")
                return self._json({"ok": True, "idle": CFG["idle"], "confirm_ops": CFG["confirm_ops"],
                                   "limits": CFG.get("limits"), "agents": _agent_labels(), "hibp_key_set": bool(_hibp_key())})
            if path == "/api/export":      # bundle encrypted with age -p using the master password
                b = self._body()
                if not verify_master(b.get("pw", "")):
                    audit("export_fail", source="web"); return self._json({"error": "bad_pw"}, 403)
                try: blob = _cer_wrap(export_bundle(b.get("pw", "")))   # opaque .cerbak container (see make_backup)
                except Exception as ex: return self._json({"error": scrub(ex)}, 500)
                audit("export", source="web", detail=f"{len(secs(load()))} secrets")
                return self._json({"ok": True, "filename": f"concealer-export-{now_iso()[:10]}{CER_EXT}",
                                   "b64": base64.b64encode(blob).decode()})
            if path == "/api/import":      # pw = the bundle's password (may not be the local master)
                b = self._body()
                try: blob = base64.b64decode(b.get("b64", ""))
                except Exception: return self._json({"error": "corrupt"}, 400)   # code → localized in webui (imp_corrupt)
                mode = b.get("mode", "overwrite")
                if mode not in ("overwrite", "skip", "duplicate"): mode = "overwrite"
                try: nn, nu, ns = import_bundle(b.get("pw", ""), blob, mode)
                except Exception as ex: return self._json({"error": scrub(ex)}, 400)
                audit("import", source="web", detail=f"mode={mode} +{nn} ~{nu} ={ns}")
                return self._json({"ok": True, "imported": nn, "updated": nu, "skipped": ns})
            if path == "/api/backup":      # manual .cer download — BACKUP password (different from master, required)
                b = self._body(); pw = b.get("pw", "")
                if len(pw) < 8: return self._json({"error": "backup_pw_short"}, 400)
                if pw != b.get("pw2", ""): return self._json({"error": "backup_pw_mismatch"}, 400)
                if verify_master(pw): return self._json({"error": "backup_pw_same_as_master"}, 400)
                try: blob = make_backup(pw)
                except Exception as ex: return self._json({"error": scrub(ex)}, 500)
                audit("backup", source="web", detail=f"{len(secs(load()))} secrets")
                return self._json({"ok": True, "filename": _cer_name(), "b64": base64.b64encode(blob).decode()})
            if path == "/api/backup/config":   # auto-backup config — master pw required (sensitive)
                b = self._body()
                if not verify_master(b.get("pw", "")):
                    audit("backup_cfg_fail", source="web"); return self._json({"error": "bad_pw"}, 403)
                c = _backup_cfg()
                c["enabled"] = bool(b.get("enabled"))
                try: c["interval_h"] = max(1, min(8760, int(b.get("interval_h", c["interval_h"]))))
                except Exception: pass
                try: c["keep"] = max(1, min(365, int(b.get("keep", c["keep"]))))
                except Exception: pass
                if isinstance(b.get("dir"), str): c["dir"] = b["dir"].strip()
                bp = b.get("backup_pw", "")
                if bp:                                          # set a new backup password → wrap to the age pubkey
                    if len(bp) < 8: return self._json({"error": "backup_pw_short"}, 400)
                    if verify_master(bp): return self._json({"error": "backup_pw_same_as_master"}, 400)
                    try: c["pw_wrapped"] = base64.b64encode(_age_enc_pub(bp)).decode()
                    except Exception as ex: return self._json({"error": scrub(ex)}, 500)
                if c["enabled"] and not c.get("pw_wrapped"):
                    return self._json({"error": "backup_pw_required"}, 400)
                _save_backup_cfg(c)
                audit("backup_cfg", source="web", detail=f"enabled={c['enabled']} every={c['interval_h']}h keep={c['keep']}")
                return self._json({"ok": True, "enabled": c["enabled"], "interval_h": c["interval_h"], "dir": c["dir"],
                                   "keep": c["keep"], "last": c["last"], "has_pw": bool(c.get("pw_wrapped"))})
            if path == "/api/backup/run":      # write the auto-backup to disk now (test/manual trigger)
                try: p = run_auto_backup()
                except Exception as ex: return self._json({"error": scrub(ex)}, 400)
                return self._json({"ok": True, "path": p})
            if path == "/api/deploy":
                b = self._body(); target = b.get("target", "dotenv")
                if b.get("id"):                       # single secret (row-level deploy)
                    e = by_id(load(), b["id"])
                    if not e: return self._json({"error": "not found"}, 404)
                    audit("deploy", key=e["name"], source="web", detail=f"{target} {label(e)}")
                    return self._json({"text": deploy_render_one(e, target), "targets": DEPLOY_TARGETS})
                scope = {dim: b.get(dim, "") for dim in DIMS if b.get(dim)}
                audit("deploy", source="web", detail=f"{target} {label(scope)}")
                return self._json({"text": deploy_render(scope, target), "targets": DEPLOY_TARGETS})
            if path == "/api/scan/import":
                b = self._body(); root = b.get("path", ""); names = set(b.get("names") or [])
                cands = [c for c in scan_folder(root, b.get("history", False), b.get("env", False)) if c["name"] in names]
                with _vault_lock():
                    d = load(); scope = {dim: b.get(dim, "") for dim in DIMS}
                    if not scope["project"] and root:
                        scope["project"] = os.path.basename(os.path.abspath(os.path.expanduser(root)))
                    n_new, n_skip = _import_cands(d, cands, scope); save(d)
                audit("scan_import", key=f"{n_new} secrets", source="scan", detail=root)
                return self._json({"imported": n_new, "skipped": n_skip})
            if path == "/api/history/purge":
                b = self._body(); targets = b.get("targets") or []
                n = history_purge(targets); audit("history_purge", key=f"{n} lines", source="web")
                return self._json({"removed": n})
            self._json({"error": "not found"}, 404)

        def do_PUT(self):
            if not self._guard(): return
            path = urllib.parse.urlparse(self.path).path
            if not valid(self._tok() or ""): return self._json({"error": "locked"}, 401)
            if path.startswith("/api/secret/"):
                with _vault_lock():
                    sid = path.rsplit("/", 1)[-1]; d = load(); e = by_id(d, sid)
                    if not e: return self._json({"error": "not found"}, 404)
                    b = self._body(); ne = _entry_from_body(b)
                    for k in ["name", "type"] + DIMS + ["tags", "url", "notes", "fields", "collection", "rotation"]: e[k] = ne[k]
                    if "field_meta" in ne: e["field_meta"] = ne["field_meta"]   # write only if sent (preserves TUI overrides)
                    e["updated"] = now_iso(); save(d)
                audit("update", key=e["name"], source="web", detail=label(e))
                return self._json({"ok": True})
            self._json({"error": "not found"}, 404)

        def do_DELETE(self):
            if not self._guard(): return
            path = urllib.parse.urlparse(self.path).path
            if not valid(self._tok() or ""): return self._json({"error": "locked"}, 401)
            if path.startswith("/api/policies/"):
                pid = path.rsplit("/", 1)[-1]
                ok = policy_delete(pid); audit("policy_delete", key=pid, source="web")
                return self._json({"ok": ok})
            if path.startswith("/api/secret/"):
                with _vault_lock():
                    sid = path.rsplit("/", 1)[-1]; d = load(); e = by_id(d, sid)
                    if not e: return self._json({"error": "not found"}, 404)
                    if "delete" in CFG["confirm_ops"] and not verify_master(self._body().get("pw", "")):
                        return self._json({"error": "bad_pw"}, 403)
                    tombstone(d, e); save(d)
                audit("delete", key=e["name"], source="web", detail=label(e))
                return self._json({"ok": True})
            self._json({"error": "not found"}, 404)

    try:
        srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), H)
    except OSError as e:
        if e.errno in (48, 98, 10048):   # EADDRINUSE (mac / linux / win): a server is already up
            print(f"concealer web already running on http://127.0.0.1:{port} — opening it")
            if os.environ.get("CONCEALER_NO_OPEN") != "1":
                try: webbrowser.open(f"http://127.0.0.1:{port}")
                except Exception: pass
            return
        raise
    # Opt-in idle self-exit: when started on-demand (e.g. by the Chrome extension's native
    # host) the process shuts itself down after N idle seconds so nothing lingers in the
    # background. Off for a normal `cer web` (env unset). Keys are already dropped by idle-lock.
    _idle_exit = int(os.environ.get("CONCEALER_WEB_IDLE_EXIT") or 0)
    if _idle_exit > 0:
        def _watchdog():
            while True:
                time.sleep(30)
                if time.time() - _last[0] > _idle_exit: os._exit(0)
        threading.Thread(target=_watchdog, daemon=True).start()
    print(f"concealer web: http://127.0.0.1:{port}  (idle-lock {CFG['idle']}s, Ctrl+C to stop)")
    if os.environ.get("CONCEALER_NO_OPEN") != "1":  # ponytail: skip in headless/SSH via env
        try: webbrowser.open(f"http://127.0.0.1:{port}")
        except Exception: pass
    try: srv.serve_forever()
    except KeyboardInterrupt: pass

def _entry_from_body(b):
    e = {"name": b.get("name", ""), "type": b.get("type", "api_key"),
         "tags": [t.strip() for t in (b.get("tags") or []) if (t or "").strip()] if isinstance(b.get("tags"), list)
                 else [t.strip() for t in str(b.get("tags", "")).split(",") if t.strip()],
         "url": b.get("url", ""), "notes": b.get("notes", ""), "fields": _clean_fields(b.get("fields", {}))[0],
         "collection": (b.get("collection") or "").strip().strip("/"),
         "rotation": b.get("rotation") if isinstance(b.get("rotation"), dict) else {}}
    for dim in DIMS: e[dim] = b.get(dim, "")
    if isinstance(b.get("field_meta"), dict): e["field_meta"] = b["field_meta"]   # record-specific secrecy overrides
    if "id" in b: e["id"] = b["id"]
    return e

# ---------------- MCP ----------------
# Delivered to EVERY MCP client on `initialize` (not just Claude Code). This is the managed,
# server-side secrets policy — it travels with the connection, unlike a per-agent local file.
# Advisory by protocol; the non-bypassable guards are code: registered-agent gate, rate_gate, redaction.
MCP_INSTRUCTIONS = (
    "concealer is a local-only secret manager. Never print, echo, cat, or write secret VALUES — "
    "they are injected into a child env and redacted from output. "
    "LEAST-PRIVILEGE (required): when calling run_with_secrets, pass `names` with ONLY the secrets the "
    "command needs; do NOT inject a whole scope. Discover names with list_secrets/search_secrets first. "
    "Scope every call as narrowly as you can (tenant/project/environment/repo). "
    "Bulk enumeration is rate-limited and audited; injecting more than you use will be flagged."
)
_DIMPROPS = {d: {"type": "string"} for d in DIMS}
MCP_TOOLS = [
    {"name": "list_secrets", "description": "List secrets by type+scope+tag+collection (no values returned).",
     "inputSchema": {"type": "object", "properties": {**_DIMPROPS, "tag": {"type": "string"}, "type": {"type": "string"},
        "collection": {"type": "string", "description": "narrow by collection path (sub-paths included)"}}}},
    {"name": "search_secrets", "description": "Search across name/scope/tag/url/notes (no values returned).",
     "inputSchema": {"type": "object", "properties": {"term": {"type": "string"}}, "required": ["term"]}},
    {"name": "run_with_secrets", "description": "Run a command with scope-matching secrets injected into env. No values leak; output is masked. Pass 'names' to inject ONLY the secrets you need (least-privilege) instead of the whole scope. All types are injected, including website/login (as NAME_USERNAME, NAME_PASSWORD, NAME_WEB_URL, ...). Env names are sanitized to valid identifiers (upper-case; non-[A-Z0-9_] -> _; e.g. 'grafana-prod' password -> GRAFANA_PROD_PASSWORD); the exact injected identifiers are listed on an 'injected:' line and in the child's CONCEALER_INJECTED env var.",
     "inputSchema": {"type": "object", "properties": {"command": {"type": "string"},
        "names": {"type": "array", "items": {"type": "string"}, "description": "restrict injection to these secret names (default: all matching the scope)"},
        **_DIMPROPS}, "required": ["command"]}},
    {"name": "set_secret", "description": "Create/update a secret (WRITES the value, never returns it). Updates if the same name+scope exists. Identify yourself with 'actor'; audit source=mcp.",
     "inputSchema": {"type": "object", "properties": {
        "name": {"type": "string"}, "type": {"type": "string", "description": "api_key|database|website|custom"},
        "value": {"type": "string", "description": "single value for api_key"},
        "fields": {"type": "object", "description": "{field: value} for multi-field types"},
        "tags": {"type": "array", "items": {"type": "string"}}, "url": {"type": "string"},
        "notes": {"type": "string"}, "actor": {"type": "string", "description": "identity of the acting agent"},
        "collection": {"type": "string", "description": "free-form grouping path (optional)"},
        "env_alias": {"type": "string", "description": "pin a stable env-injection identifier base (e.g. 'GRAFANA'); '' derives from name"},
        **_DIMPROPS}, "required": ["name"]}},
    {"name": "request_web_login", "description": "Browser counterpart of run_with_secrets: ask concealer to type a stored sign-in (account id/alias, username, password) into the login form of the browser tab you are on, WITHOUT the value ever reaching you. Works for any record with a password field and a URL (website/login, or custom records like an AWS console login with account_id/username/password). A human approves on the page or in the app (\"This task\" approval auto-approves repeats for 15 min); the concealer extension fills the form. Multi-step forms (e.g. AWS root: e-mail page, then password page) are handled: after the first page you click Next and the extension fills the password on the next page by itself. When several secrets match the site (e.g. multiple AWS accounts), find the right one with search_secrets and pass its exact `name`. Returns ONLY a status string — never the password. Requires the concealer app running and its browser extension.",
     "inputSchema": {"type": "object", "properties": {
        "target_url": {"type": "string", "description": "URL/origin of the login page you are on"},
        "name": {"type": "string", "description": "optional exact secret name; else concealer matches by domain"},
        **_DIMPROPS}, "required": ["target_url"]}},
]
def _fmt(rows): return "\n".join(f"{e['name']:22} {e['type']:9} {label(e):22} [{','.join(e['tags'])}]" for e in rows) or "(empty)"
def _mcp_call(name, args):
    # Registration required: only 'agent' source tokens can access secrets from MCP (unregistered agent = fail-closed).
    agent, source = _mcp_agent()
    if source != "agent":
        return ("error: access denied — a registered agent token is required. "
                "First, the vault owner: `concealer agent register <name>` and put the generated CONCEALER_TOKEN in the MCP env.")
    if name == "list_secrets":
        sel = {d: args[d] for d in DIMS if args.get(d)}
        rows = filt(load(), sel, args.get("tag"), None, args.get("type"), args.get("collection"))
        allowed, note = rate_gate(agent, rows)
        audit("list", source="mcp", detail=json.dumps(sel), actor=agent)
        return _fmt(allowed) + note
    if name == "search_secrets":
        rows = filt(load(), term=args.get("term"))
        allowed, note = rate_gate(agent, rows)
        audit("search", source="mcp", detail=args.get("term", ""), actor=agent)
        return _fmt(allowed) + note
    if name == "run_with_secrets":
        target = {d: args[d] for d in DIMS if args.get(d)}
        for dim in ("repo", "project"): target.setdefault(dim, detect(dim))
        env, d, note = inject_env(target, source="mcp", actor=agent, command=args["command"], gate=agent, names=args.get("names"))
        if env is None: return "error: injection blocked — rate limit reached." + (note or "")
        r = subprocess.run(["/bin/sh", "-c", args["command"]], env=env, capture_output=True, text=True)
        head = f"[{label(target)}]"
        if env.get("CONCEALER_INJECTED"): head += f"\ninjected: {env['CONCEALER_INJECTED']}"   # identifier names only
        return redact(head + "\n" + r.stdout + r.stderr, d) or "(no output)"
    if name == "request_web_login":
        target = args.get("target_url", ""); tok = os.environ.get("CONCEALER_TOKEN", "")
        body = {"target_url": target, "name": args.get("name", "")}
        for dim in DIMS:
            if args.get(dim): body[dim] = args[dim]
        try: r0 = _af_local("POST", "/api/autofill/request", tok, body)
        except Exception:
            return f"pending: the concealer app isn't reachable on 127.0.0.1:{AF_PORT} — open concealer and unlock, then retry"
        if "job" not in r0:   # immediate terminal: locked / no match / domain mismatch / rate limited
            st = r0.get("status", "error")
            return "pending: concealer is locked — unlock it in the app, then retry" if st == "locked" else st
        jid = r0["job"]; dom = registrable_domain(_af_host(target)); deadline = time.time() + 90
        while time.time() < deadline:
            time.sleep(1.0)
            try: st = _af_local("GET", f"/api/autofill/status?job={jid}", tok); s = st.get("status")
            except Exception: st, s = {}, None
            if s in ("done", "denied", "failed", "expired"):
                audit("web_autofill_result", key=args.get("name", "") or dom, source="mcp", detail=s, actor=agent)
                return {"done": f"filled: {args.get('name') or dom}", "denied": "denied by user",
                        "failed": "fill failed on the page" + (f" ({st.get('result')})" if st.get("result") else ""), "expired": "expired: no approval or no extension on this tab"}[s]
        return "pending: waiting for approval or for the concealer extension on this tab"
    if name == "set_secret":
        actor = args.get("actor") or agent or os.environ.get("CONCEALER_ACTOR", "")
        d = load(); ident = {dim: args.get(dim, "") for dim in DIMS}; ident["name"] = args["name"]
        hit = next((e for e in secs(d) if matches(e, ident)), None)
        fields = dict(args.get("fields") or {})
        if args.get("value") is not None and "value" not in fields: fields["value"] = args["value"]
        fields, bad = _clean_fields(fields)   # reject fields with secret-like (leaked) names
        if bad: return "error: invalid field name (looks like a secret value): " + ", ".join(mask(b) for b in bad)
        if hit:
            hit["fields"].update(fields); hit["updated"] = now_iso()
            if "tags" in args: hit["tags"] = [t for t in (args["tags"] or []) if t]
            if "url" in args: hit["url"] = args["url"]
            if "notes" in args: hit["notes"] = args["notes"]
            if "collection" in args: hit["collection"] = (args["collection"] or "").strip().strip("/")
            if "env_alias" in args: hit["env_alias"] = (args["env_alias"] or "").strip()
            act = "update"
        else:
            e = dict(ident); e["type"] = args.get("type", "api_key"); e["fields"] = fields
            e["tags"] = [t for t in (args.get("tags") or []) if t]
            e["url"] = args.get("url", ""); e["notes"] = args.get("notes", "")
            e["collection"] = (args.get("collection") or "").strip().strip("/")
            e["env_alias"] = (args.get("env_alias") or "").strip()
            secs(d).append(norm(e)); act = "create"
        save(d); audit(act, key=args["name"], source="mcp", detail=label(ident), actor=actor)
        return f"{act}: {args['name']} @ {label(ident)}"
    return f"unknown tool: {name}"
def mcp_stdio():
    def send(o): sys.stdout.write(json.dumps(o) + "\n"); sys.stdout.flush()
    for line in sys.stdin:
        line = line.strip()
        if not line: continue
        req = json.loads(line); mid = req.get("id"); m = req.get("method")
        if m == "initialize":
            send({"jsonrpc": "2.0", "id": mid, "result": {"protocolVersion": "2024-11-05",
                  "capabilities": {"tools": {}}, "serverInfo": {"name": "concealer", "version": VERSION},
                  "instructions": MCP_INSTRUCTIONS}})
        elif m == "notifications/initialized": pass
        elif m == "tools/list": send({"jsonrpc": "2.0", "id": mid, "result": {"tools": MCP_TOOLS}})
        elif m == "tools/call":
            p = req.get("params", {})
            try:
                with (_vault_lock() if p.get("name") == "set_secret" else contextlib.nullcontext()):
                    text = _mcp_call(p.get("name"), p.get("arguments", {}))
            except Exception as e: text = f"error: {scrub(e)}"
            send({"jsonrpc": "2.0", "id": mid, "result": {"content": [{"type": "text", "text": text}]}})
        elif mid is not None:
            send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"method not found: {m}"}})

def _run():   # console_scripts entry point (pipx/PyPI); flat `./concealer` still uses the guard below
    cli(sys.argv[1:])

if __name__ == "__main__":
    cli(sys.argv[1:])
