From 471e20a03503d3951a6fe12c1f3a354043a42e05 Mon Sep 17 00:00:00 2001 From: Elvis Claros Castro Date: Sat, 3 Oct 2026 12:05:23 -0300 Subject: Manage permission rules, extra directories and folder trust -P lists the allow/ask/deny rules and additionalDirectories of the user, project and local settings, plus hasTrustDialogAccepted from ~/.claude.json. --allow, --ask, --deny, --remove-rule, --add-dir, --remove-dir, --trust and --untrust edit them in place, keeping every other key, the file mode and the trailing newline; --dry-run shows the change without making it. --- README.es.md | 46 +++++++ README.md | 46 +++++++ claude_logbook/__init__.py | 2 +- claude_logbook/cli.py | 142 +++++++++++++++++++- claude_logbook/config.py | 314 +++++++++++++++++++++++++++++++++++++++++++++ claude_logbook/terminal.py | 58 +++++++++ tests/test_config.py | 246 +++++++++++++++++++++++++++++++++++ 7 files changed, 851 insertions(+), 3 deletions(-) create mode 100644 claude_logbook/config.py create mode 100644 tests/test_config.py diff --git a/README.es.md b/README.es.md index eef28ac..8bd8da5 100644 --- a/README.es.md +++ b/README.es.md @@ -61,6 +61,7 @@ claude-logbook -r 3 # imprime el comando para reanudarla eval "$(claude-logbook -r 3)" # …o la reanuda directamente claude-logbook --html --open # genera sessions.html y lo abre claude-logbook -m # las memorias de tus proyectos +claude-logbook -P # permisos, directorios extra y confianza ``` El número es la posición de la fila **en la tabla que estás viendo**, así que si @@ -92,6 +93,12 @@ claude-logbook docker -s 2 # lee el 2º de esos tres | `-m`, `--memory` | Trabaja sobre las memorias en vez de las sesiones. | | `--type TYPE` | Con `-m`: filtra por `project`, `user`, `feedback` o `reference`. | | `--check` | Con `-m`: audita índices, enlaces y sesiones de origen. | +| `-P`, `--perms` | Lista reglas de permisos, directorios extra y confianza. | +| `--allow`, `--ask`, `--deny RULE` | Agrega una regla de permisos (ver abajo). | +| `--remove-rule RULE` | Saca una regla de `allow`, `ask` y `deny`. | +| `--add-dir`, `--remove-dir DIR` | Edita `additionalDirectories`. | +| `--trust`, `--untrust` | Acepta o reinicia el diálogo de confianza del proyecto `-p`. | +| `--scope SCOPE` | Archivo de settings a cambiar: `user`, `project` o `local`. | ### Borrar sesiones @@ -160,6 +167,44 @@ claude-logbook -m -D 3 --dry-run # qué borraría claude-logbook -m -D deploy-docker # borra esa memoria ``` +## Permisos + +Claude Code guarda sus reglas de permisos en archivos `settings.json` y la +respuesta a "¿confiás en esta carpeta?" en `~/.claude.json`. `-P` los muestra +juntos, y unos pocos flags los editan sin abrir ningún JSON: + +```bash +claude-logbook -P # reglas de usuario + proyectos con reglas +claude-logbook -P -p api # un proyecto, tenga reglas o no +claude-logbook --allow "Bash(npm test:*)" -p . +claude-logbook --deny "Read(./.env)" --scope project -p . +claude-logbook --remove-rule WebFetch # fuera de allow, ask y deny +claude-logbook --add-dir ~/shared -p . # additionalDirectories +claude-logbook --trust -p ~/code/api # marca esa carpeta como confiable +claude-logbook --untrust -p ~/code/api # Claude Code vuelve a preguntar +``` + +Adónde va cada cambio: + +| Qué | Archivo | +| --- | --- | +| Reglas y directorios, sin `-p` | `~/.claude/settings.json` (alcance de usuario) | +| Reglas y directorios con `-p` | `/.claude/settings.local.json` (personal) | +| Lo mismo, con `--scope project` | `/.claude/settings.json` (suele ir al repo) | +| `--trust` / `--untrust` | `hasTrustDialogAccepted` en `~/.claude.json` | + +`-p` acepta un directorio, o cualquier pedazo de la ruta de un proyecto que +Claude Code haya visto, siempre que coincida con uno solo. Las reglas usan la +sintaxis de Claude Code: `Tool` o `Tool(especificador)`. Una regla vive en una +sola lista, así que `--deny X` saca `X` de `allow` y `ask`. El resto de las +claves de esos archivos queda como estaba, el archivo se reemplaza de forma +atómica conservando sus permisos, y `--dry-run` muestra el cambio sin hacerlo. +Las sesiones ya abiertas pueden necesitar reiniciarse para notarlo. + +`~/.claude.json` también guarda tu cuenta y el estado de cada Claude Code en +marcha, que lo reescriben seguido: claude-logbook lo lee justo antes de +cambiarlo y reintenta si se modificó en el medio. + ## La página HTML `claude-logbook --html` genera un único archivo con los datos adentro. Sin @@ -278,6 +323,7 @@ tocan `~/.claude`. No hay nada que instalar: ni runner de tests ni dependencias. | --- | --- | | `claude_logbook/sessions.py` | Parsear los `.jsonl`, el caché, los filtros. | | `claude_logbook/memory.py` | Leer los `memory/*.md` y auditarlos. | +| `claude_logbook/config.py` | Reglas de permisos, directorios extra y confianza en carpetas. | | `claude_logbook/terminal.py` | Colores ANSI, la tabla, imprimir un chat. | | `claude_logbook/webpage.py` | Meter los datos adentro del template. | | `claude_logbook/cli.py` | Los argumentos y los comandos. | diff --git a/README.md b/README.md index c756f9a..bba8906 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,7 @@ claude-logbook -r 3 # print the command that resumes it eval "$(claude-logbook -r 3)" # …or resume it right away claude-logbook --html --open # build sessions.html and open it claude-logbook -m # your projects' memories +claude-logbook -P # permissions, extra directories and trust ``` The number is the row's position **in the table you are looking at**, so if you @@ -92,6 +93,12 @@ claude-logbook docker -s 2 # reads the 2nd of those three | `-m`, `--memory` | Work on memories instead of sessions. | | `--type KIND` | With `-m`: filter by `project`, `user`, `feedback` or `reference`. | | `--check` | With `-m`: audit indexes, links and origin sessions. | +| `-P`, `--perms` | List permission rules, extra directories and folder trust. | +| `--allow`, `--ask`, `--deny RULE` | Add a permission rule (see below). | +| `--remove-rule RULE` | Remove a rule from `allow`, `ask` and `deny`. | +| `--add-dir`, `--remove-dir DIR` | Edit `additionalDirectories`. | +| `--trust`, `--untrust` | Accept or reset the trust dialog of the `-p` project. | +| `--scope SCOPE` | Settings file to change: `user`, `project` or `local`. | ### Deleting sessions @@ -159,6 +166,44 @@ claude-logbook -m -D 3 --dry-run # what it would delete claude-logbook -m -D deploy-docker # delete that memory ``` +## Permissions + +Claude Code keeps its permission rules in `settings.json` files and the +"do you trust this folder?" answer in `~/.claude.json`. `-P` shows them all +together, and a handful of flags edit them without opening any JSON: + +```bash +claude-logbook -P # user rules + every project with rules +claude-logbook -P -p api # one project, with or without rules +claude-logbook --allow "Bash(npm test:*)" -p . +claude-logbook --deny "Read(./.env)" --scope project -p . +claude-logbook --remove-rule WebFetch # out of allow, ask and deny +claude-logbook --add-dir ~/shared -p . # additionalDirectories +claude-logbook --trust -p ~/code/api # mark that folder as trusted +claude-logbook --untrust -p ~/code/api # Claude Code will ask again +``` + +Where each change goes: + +| What | File | +| --- | --- | +| Rules and directories, no `-p` | `~/.claude/settings.json` (user scope) | +| Rules and directories with `-p` | `/.claude/settings.local.json` (personal) | +| Same, with `--scope project` | `/.claude/settings.json` (usually committed) | +| `--trust` / `--untrust` | `hasTrustDialogAccepted` in `~/.claude.json` | + +`-p` takes a directory, or any piece of a project path Claude Code has seen as +long as it matches only one. Rules use Claude Code's syntax: `Tool` or +`Tool(specifier)`. A rule lives in one list only, so `--deny X` takes `X` out of +`allow` and `ask`. Every other key in those files is kept as it was, the file is +replaced atomically with its permissions intact, and `--dry-run` shows the +change without making it. Sessions that are already open may need a restart to +notice. + +`~/.claude.json` also holds your account and the state of every running Claude +Code, which rewrite it often: claude-logbook reads it right before changing it, +and retries if it moves in between. + ## The HTML page `claude-logbook --html` produces one file with the data embedded inside it. No @@ -277,6 +322,7 @@ The tests build fake `.jsonl` trees in a temporary directory and never touch | --- | --- | | `claude_logbook/sessions.py` | Parsing the `.jsonl` files, the cache, filters. | | `claude_logbook/memory.py` | Reading the `memory/*.md` files and auditing them. | +| `claude_logbook/config.py` | Permission rules, extra directories and folder trust. | | `claude_logbook/terminal.py` | ANSI colours, the table, printing a conversation. | | `claude_logbook/webpage.py` | Embedding the data into the template. | | `claude_logbook/cli.py` | Argument parsing and the commands. | diff --git a/claude_logbook/__init__.py b/claude_logbook/__init__.py index 077c904..abe9c71 100644 --- a/claude_logbook/__init__.py +++ b/claude_logbook/__init__.py @@ -3,6 +3,6 @@ No dependencies: standard library only. """ -__version__ = "1.2.0" +__version__ = "1.3.0" __all__ = ["__version__"] diff --git a/claude_logbook/cli.py b/claude_logbook/cli.py index 6b1ebc2..43b08eb 100644 --- a/claude_logbook/cli.py +++ b/claude_logbook/cli.py @@ -15,8 +15,10 @@ from .sessions import ( ) from .terminal import ( Style, clip, fmt_date, fmt_size, plural, print_audit, print_chat, - print_memories, print_memory, print_table, resume_cmd, + print_memories, print_memory, print_permissions, print_table, resume_cmd, + short_home, ) +from . import config as cfg from . import memory as mem from . import webpage @@ -56,6 +58,18 @@ verbs: filter, -s to read, -D to delete): claude-logbook -m -s deadlock same, by name claude-logbook -m --check audit indexes, links and sources claude-logbook -m -D 3 delete it and drop it from MEMORY.md + +permissions (-P lists them; any change flag implies it). Rules go to the +user settings unless -p names a project, then to its settings.local.json; +--scope project writes the shared .claude/settings.json instead: + claude-logbook -P user rules and every project with rules + claude-logbook -P -p logbook one project, trusted or not + claude-logbook --allow "Bash(npm test:*)" -p . + claude-logbook --deny "Read(./.env)" --scope project -p . + claude-logbook --remove-rule WebFetch drop it from allow, ask and deny + claude-logbook --add-dir ~/shared -p . extra directory for that project + claude-logbook --trust -p ~/repo accept the trust dialog for it + claude-logbook --untrust -p ~/repo --dry-run """ @@ -93,6 +107,28 @@ def build_parser(): memories_list.add_argument("--check", action="store_true", help="audit indexes, links and source sessions") + perms = ap.add_argument_group("permissions") + perms.add_argument("-P", "--perms", action="store_true", + help="work on permissions instead of sessions") + for key, what in (("allow", "allowed without asking"), + ("ask", "always asked"), ("deny", "denied")): + perms.add_argument(f"--{key}", metavar="RULE", nargs="+", action="extend", + help=f"add a rule to {key}: {what}") + perms.add_argument("--remove-rule", metavar="RULE", nargs="+", action="extend", + help="remove a rule from allow, ask and deny") + perms.add_argument("--add-dir", metavar="DIR", nargs="+", action="extend", + help="add to additionalDirectories") + perms.add_argument("--remove-dir", metavar="DIR", nargs="+", action="extend", + help="remove from additionalDirectories") + trust = perms.add_mutually_exclusive_group() + trust.add_argument("--trust", action="store_true", + help="mark the -p project as trusted in ~/.claude.json") + trust.add_argument("--untrust", action="store_true", + help="make Claude Code ask again whether to trust it") + perms.add_argument("--scope", choices=cfg.SCOPES, + help="settings file to change (default: local with -p, " + "user without)") + output_path = ap.add_argument_group("export") output_path.add_argument("--json", action="store_true", help="dump every session as JSON") @@ -111,7 +147,7 @@ def build_parser(): delete_items.add_argument("-y", "--yes", action="store_true", help="do not ask before deleting") delete_items.add_argument("--dry-run", action="store_true", - help="show what would be deleted and touch nothing") + help="show what would change and touch nothing") ap.add_argument("--no-cache", action="store_true", help="ignore the cache and re-parse everything") @@ -403,7 +439,109 @@ def run_memory(sessions, args, st): return cmd_mem_table(mem_filtered(memories, args), args, st, len(memories)) +# ──────────────────────────────── permissions ───────────────────────────── + +PERM_EDITS = ("allow", "ask", "deny", "remove_rule", "add_dir", "remove_dir", + "trust", "untrust") + + +def wants_perms(args): + return args.perms or any(getattr(args, k) for k in PERM_EDITS) + + +def known_projects(sessions): + return {s["p"] for s in sessions} | set(cfg.trusted_projects()) + + +def cmd_perms_list(sessions, args, st): + view = cfg.overview({s["p"] for s in sessions}) + needles = [n.lower() for n in + ([os.path.expanduser(args.project).rstrip("/")] if args.project else []) + + list(args.query)] + if needles: + view["projects"] = [p for p in view["projects"] + if all(n in p["path"].lower() for n in needles)] + shown = print_permissions(view, st, sys.stdout, show_all=bool(needles)) + + trusted = sum(1 for p in view["projects"] if p["trusted"]) + if needles and not view["projects"]: + print(f"\n{st.faint}no project matches that filter{st.reset}") + return 1 + hidden = len(view["projects"]) - shown + tail = f"{trusted} of {plural(len(view['projects']), 'project', 'projects')} trusted" + if hidden: + tail += f" · {hidden} without rules not shown (-p to see one)" + print(f"\n{st.faint}{tail}{st.reset}") + return 0 + + +def cmd_perms_edit(sessions, args, st): + project = None + if args.project: + project = cfg.resolve_project(args.project, known_projects(sessions)) + if (args.trust or args.untrust) and not project: + raise SessionError("--trust and --untrust need a project: -p PATH (-p . for here)") + + changes = [] + for key in cfg.LISTS: + changes += [("add", key, cfg.check_rule(r)) for r in getattr(args, key) or []] + changes += [("forget", r.strip()) for r in args.remove_rule or []] + changes += [("add-dir", cfg.normalize_dir(d)) for d in args.add_dir or []] + changes += [("remove-dir", cfg.normalize_dir(d)) for d in args.remove_dir or []] + + for d in args.add_dir or []: + if not os.path.isdir(cfg.normalize_dir(d)): + print(f"{st.copper}warning: {d} is not a directory (added anyway){st.reset}", + file=sys.stderr) + + verb = "would change" if args.dry_run else "changed" + touched = False + + if changes: + scope = args.scope or ("local" if project else "user") + path = cfg.settings_path(scope, project) + steps = cfg.edit_settings(path, changes, dry_run=args.dry_run) + if steps: + touched = True + print(f"{st.bold}{scope}{st.reset} {st.faint}{short_home(path)}{st.reset}") + for step in steps: + print(f" {step}") + else: + print(f"{st.faint}{short_home(path)}: already like that{st.reset}") + + if args.trust or args.untrust: + value = bool(args.trust) + state = short_home(cfg.global_state_path()) + if cfg.set_trust(project, value, dry_run=args.dry_run): + touched = True + word = "trusted" if value else "not trusted" + print(f"{st.bold}trust{st.reset} {st.faint}{state}{st.reset}") + print(f" {short_home(project)} → {word}") + else: + print(f"{st.faint}{state}: {short_home(project)} already " + f"{'trusted' if value else 'not trusted'}{st.reset}") + + if args.dry_run and touched: + print(f"\n{st.faint}--dry-run: nothing was touched.{st.reset}") + elif touched: + print(f"\n{st.faint}{verb}; Claude Code sessions already open may need " + f"a restart to see it.{st.reset}") + return 0 + + +def run_perms(args, st): + root = default_root() + sessions = (load_sessions(root=root, use_cache=not args.no_cache) + if os.path.isdir(root) else []) + if any(getattr(args, k) for k in PERM_EDITS): + return cmd_perms_edit(sessions, args, st) + return cmd_perms_list(sessions, args, st) + + def run(args): + if wants_perms(args): + return run_perms(args, Style.from_stream(sys.stdout, args.no_color)) + root = default_root() if not os.path.isdir(root): print(f"error: {root} does not exist — have you used Claude Code on this machine?", diff --git a/claude_logbook/config.py b/claude_logbook/config.py new file mode 100644 index 0000000..96c2e48 --- /dev/null +++ b/claude_logbook/config.py @@ -0,0 +1,314 @@ +"""Claude Code permissions: tool rules, extra directories and folder trust. + +They live in three kinds of files: + + ~/.claude/settings.json user scope, every project + /.claude/settings.json project scope, usually committed + /.claude/settings.local.json local scope, personal, git-ignored + +each with a `permissions` object: + + {"permissions": {"allow": [...], "deny": [...], "ask": [...], + "additionalDirectories": [...]}} + +Trust is elsewhere: `~/.claude.json` keeps one entry per absolute project path, +and `hasTrustDialogAccepted` in it records that the "do you trust this folder?" +dialog was accepted. That file also holds the account and every other piece of +Claude Code state, so it is rewritten keeping all of it as it was. + +Every write is read-modify-replace: the file is read again right before the +change and swapped in atomically, keeping its permissions. +""" + +import json +import os +import re +import tempfile + +from .sessions import SessionError + +SCOPES = ("user", "project", "local") +LISTS = ("allow", "deny", "ask") +DIRS_KEY = "additionalDirectories" +TRUST_KEY = "hasTrustDialogAccepted" + +# Tool, Tool(specifier) or mcp__server__tool. The specifier is free text. +RULE_RE = re.compile(r"^[A-Za-z][\w.-]*(\(.*\))?$", re.S) + + +# ──────────────────────────────── locations ────────────────────────────────── + +def config_dir(): + return os.environ.get("CLAUDE_CONFIG_DIR") or os.path.join( + os.path.expanduser("~"), ".claude") + + +def global_state_path(): + """~/.claude.json, or .claude.json inside CLAUDE_CONFIG_DIR if it is set.""" + if os.environ.get("CLAUDE_CONFIG_DIR"): + return os.path.join(os.environ["CLAUDE_CONFIG_DIR"], ".claude.json") + return os.path.join(os.path.expanduser("~"), ".claude.json") + + +def settings_path(scope, project=None): + if scope == "user": + return os.path.join(config_dir(), "settings.json") + if not project: + raise SessionError(f"the {scope} scope needs a project (-p PATH)") + name = "settings.json" if scope == "project" else "settings.local.json" + return os.path.join(project, ".claude", name) + + +# ──────────────────────────────── files ─────────────────────────────────── + +def read_json(path): + """The file's object, {} if it does not exist. Broken JSON is an error: + rewriting it would lose whatever it had.""" + try: + with open(path, encoding="utf-8") as fh: + text = fh.read() + except FileNotFoundError: + return {} + except OSError as e: + raise SessionError(f"cannot read {path}: {e.strerror}") + if not text.strip(): + return {} + try: + data = json.loads(text) + except ValueError as e: + raise SessionError(f"{path} is not valid JSON ({e}); fix it by hand first") + if not isinstance(data, dict): + raise SessionError(f"{path} does not hold a JSON object") + return data + + +def write_json(path, data): + """Atomic replace that keeps the file's mode (0644 minus umask if new) and + whether it ended in a newline, so an untouched key reads exactly the same.""" + try: + mode = os.stat(path).st_mode & 0o777 + with open(path, "rb") as fh: + fh.seek(0, os.SEEK_END) + if fh.tell(): + fh.seek(-1, os.SEEK_END) + newline = fh.read(1) == b"\n" + else: + newline = True + except FileNotFoundError: + umask = os.umask(0) + os.umask(umask) + mode = 0o666 & ~umask + newline = True + folder = os.path.dirname(path) or "." + os.makedirs(folder, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=folder, prefix=".tmp-", suffix=".json") + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(data, fh, indent=2, ensure_ascii=False) + if newline: + fh.write("\n") + os.chmod(tmp, mode) + os.replace(tmp, path) + except BaseException: + try: + os.remove(tmp) + except OSError: + pass + raise + + +# ──────────────────────────────── reading ─────────────────────────────────── + +def permissions_of(data): + perms = data.get("permissions") + return perms if isinstance(perms, dict) else {} + + +def rules(data): + """{"allow": [...], "deny": [...], "ask": [...], "dirs": [...], "mode": str}""" + perms = permissions_of(data) + out = {k: [r for r in perms.get(k) or [] if isinstance(r, str)] for k in LISTS} + out["dirs"] = [d for d in perms.get(DIRS_KEY) or [] if isinstance(d, str)] + out["mode"] = perms.get("defaultMode") if isinstance( + perms.get("defaultMode"), str) else None + return out + + +def is_empty(r): + return not any(r[k] for k in (*LISTS, "dirs", "mode")) + + +def trusted_projects(state=None): + """{path: bool} for every project ~/.claude.json knows about.""" + state = read_json(global_state_path()) if state is None else state + projects = state.get("projects") + if not isinstance(projects, dict): + return {} + return {p: bool(v.get(TRUST_KEY)) for p, v in projects.items() + if isinstance(v, dict)} + + +def trusted_parent(path, trust): + """Closest trusted ancestor of `path`, or None.""" + cur = path + while True: + parent = os.path.dirname(cur) + if parent == cur: + return None + if trust.get(parent): + return parent + cur = parent + + +def overview(project_paths): + """User scope plus one entry per project, for the listing.""" + trust = trusted_projects() + user_path = settings_path("user") + projects = [] + for p in sorted(set(project_paths) | set(trust)): + scopes = [] + for scope in ("project", "local"): + path = settings_path(scope, p) + scopes.append({"scope": scope, "path": path, + "rules": rules(read_json(path))}) + projects.append({"path": p, "trusted": trust.get(p, False), + "parent": trusted_parent(p, trust), + "exists": os.path.isdir(p), "scopes": scopes}) + return {"user": {"scope": "user", "path": user_path, + "rules": rules(read_json(user_path))}, + "projects": projects} + + +# ──────────────────────────────── targets ─────────────────────────────────── + +def resolve_project(ref, known): + """An existing directory, or the only known project whose path contains `ref`.""" + expanded = os.path.expanduser(ref) + if os.path.isdir(expanded): + return os.path.abspath(expanded).rstrip("/") or "/" + needle = expanded.rstrip("/").lower() + hits = sorted({p for p in known if needle in p.lower()}) + if len(hits) == 1: + return hits[0] + if not hits: + raise SessionError(f"{ref} is not a directory nor a known project") + shown = "\n ".join(hits[:8]) + ("\n …" if len(hits) > 8 else "") + raise SessionError(f"{ref} is ambiguous, it matches {len(hits)} projects:\n {shown}") + + +def check_rule(rule): + rule = rule.strip() + if not RULE_RE.match(rule) or rule.count("(") != rule.count(")"): + raise SessionError( + f"{rule!r} does not look like a rule: Tool or Tool(specifier), " + f"e.g. Bash(npm test:*), Read(./secrets/**), WebFetch") + return rule + + +def normalize_dir(d): + return os.path.abspath(os.path.expanduser(d)).rstrip("/") or "/" + + +# ──────────────────────────────── changes ─────────────────────────────────── +# +# Each change is a tuple and `plan` turns them into human-readable steps +# against the current contents, so --dry-run and the real run say the same. +# +# ("add", list, rule) ("forget", rule) +# ("add-dir", path) ("remove-dir", path) + +def apply_rules(data, changes): + """Applies the changes to `data` in place. Returns the list of steps done; + a change that is already in effect produces no step.""" + perms = data.get("permissions") + if not isinstance(perms, dict): + perms = {} + steps = [] + + def lst(key): + cur = perms.get(key) + return cur if isinstance(cur, list) else [] + + for change in changes: + kind = change[0] + if kind == "add": + _, target, rule = change + for other in LISTS: + if other != target and rule in lst(other): + perms[other] = [r for r in lst(other) if r != rule] + steps.append(f"{rule} leaves {other}") + if rule not in lst(target): + perms[target] = lst(target) + [rule] + steps.append(f"{target} {rule}") + elif kind == "forget": + _, rule = change + for key in LISTS: + if rule in lst(key): + perms[key] = [r for r in lst(key) if r != rule] + steps.append(f"{rule} leaves {key}") + elif kind == "add-dir": + _, d = change + if d not in lst(DIRS_KEY): + perms[DIRS_KEY] = lst(DIRS_KEY) + [d] + steps.append(f"directory {d}") + elif kind == "remove-dir": + _, d = change + gone = [x for x in lst(DIRS_KEY) if x == d or normalize_dir(x) == d] + if gone: + perms[DIRS_KEY] = [x for x in lst(DIRS_KEY) if x not in gone] + steps.append(f"directory {d} removed") + + # Lists left empty are dropped, and so is an empty permissions object. + for key in (*LISTS, DIRS_KEY): + if key in perms and perms[key] == []: + del perms[key] + if perms: + data["permissions"] = perms + else: + data.pop("permissions", None) + return steps + + +def edit_settings(path, changes, dry_run=False): + data = read_json(path) + steps = apply_rules(data, changes) + if steps and not dry_run: + write_json(path, data) + return steps + + +def set_trust(project, value, dry_run=False): + """Sets hasTrustDialogAccepted for that path. Returns whether it changed. + + ~/.claude.json is rewritten by every running Claude Code, so it is read + right before writing and the write is retried if the file moved under us. + """ + path = global_state_path() + for _ in range(3): + try: + before = os.stat(path).st_mtime_ns + except FileNotFoundError: + before = None + state = read_json(path) + projects = state.setdefault("projects", {}) + if not isinstance(projects, dict): + raise SessionError(f"{path}: 'projects' is not an object") + entry = projects.setdefault(project, {}) + if bool(entry.get(TRUST_KEY)) == value and TRUST_KEY in entry: + return False + if not value and TRUST_KEY not in entry: + if not entry: + del projects[project] + return False + if dry_run: + return True + entry[TRUST_KEY] = value + try: + now = os.stat(path).st_mtime_ns + except FileNotFoundError: + now = None + if now != before: + continue + write_json(path, state) + return True + raise SessionError(f"{path} keeps changing (is Claude Code writing it?); try again") diff --git a/claude_logbook/terminal.py b/claude_logbook/terminal.py index 8ecd070..65af046 100644 --- a/claude_logbook/terminal.py +++ b/claude_logbook/terminal.py @@ -7,6 +7,7 @@ import subprocess import sys import textwrap +from .config import is_empty from .sessions import parse_ts MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", @@ -370,3 +371,60 @@ def print_audit(report, st, out): print(file=out) return total + + +# ──────────────────────────────── permissions ──────────────────────────── + +RULE_COLOR = {"allow": "amber", "ask": "blue", "deny": "copper", "dirs": "grey", + "mode": "grey"} + + +def _print_rules(r, st, out, indent): + for key in ("allow", "ask", "deny", "dirs"): + color = getattr(st, RULE_COLOR[key]) + for i, item in enumerate(r[key]): + label = key if i == 0 else "" + print(f"{indent}{st.faint}{label:<6}{st.reset} {color}{item}{st.reset}", + file=out) + if r["mode"]: + print(f"{indent}{st.faint}{'mode':<6}{st.reset} {r['mode']}", file=out) + + +def short_home(path): + home = os.path.expanduser("~") + return "~" + path[len(home):] if path == home or path.startswith(home + "/") else path + + +def trust_label(p, st): + if p["trusted"]: + return f"{st.amber}trusted{st.reset}" + if p["parent"]: + return f"{st.faint}not trusted · parent {short_home(p['parent'])} is{st.reset}" + return f"{st.copper}not trusted{st.reset}" + + +def print_permissions(view, st, out, show_all=False): + """User scope, then each project with rules (or every one if show_all).""" + user = view["user"] + print(f"{st.bold}user{st.reset} {st.faint}{short_home(user['path'])}{st.reset}", + file=out) + if is_empty(user["rules"]): + print(f" {st.faint}no rules{st.reset}", file=out) + else: + _print_rules(user["rules"], st, out, " ") + + shown = 0 + for p in view["projects"]: + with_rules = [s for s in p["scopes"] if not is_empty(s["rules"])] + if not with_rules and not show_all: + continue + shown += 1 + gone = "" if p["exists"] else f" {st.faint}(directory gone){st.reset}" + print(f"\n{st.ink}{short_home(p['path'])}{st.reset} {trust_label(p, st)}{gone}", + file=out) + for s in with_rules: + name = os.path.relpath(s["path"], p["path"]) + print(f" {st.grey}{s['scope']:<7}{st.reset} {st.faint}{name}{st.reset}", + file=out) + _print_rules(s["rules"], st, out, " ") + return shown diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..8b8b94a --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,246 @@ +import json +import os +import stat + +from claude_logbook import config as cfg +from claude_logbook.sessions import SessionError + +from .fixtures import simple_tree +from .test_cli import CliCase + + +class ConfigCase(CliCase): + """A fake ~/.claude (with its .claude.json) plus a real project directory.""" + + def setUp(self): + super().setUp() + self.claude = os.path.join(self.home, ".claude") + self.state = os.path.join(self.claude, ".claude.json") + self.proj = os.path.join(self.home, "work", "proj") + os.makedirs(self.proj) + + def write(self, path, data, newline=True): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + fh.write(json.dumps(data, indent=2) + ("\n" if newline else "")) + + def read(self, path): + with open(path, encoding="utf-8") as fh: + return json.load(fh) + + def local(self): + return os.path.join(self.proj, ".claude", "settings.local.json") + + +class TestLocations(ConfigCase): + def test_paths_follow_claude_config_dir(self): + self.assertEqual(cfg.global_state_path(), self.state) + self.assertEqual(cfg.settings_path("user"), + os.path.join(self.claude, "settings.json")) + self.assertEqual(cfg.settings_path("project", "/x"), "/x/.claude/settings.json") + self.assertEqual(cfg.settings_path("local", "/x"), + "/x/.claude/settings.local.json") + + def test_project_scopes_need_a_project(self): + with self.assertRaises(SessionError): + cfg.settings_path("local") + + +class TestApplyRules(ConfigCase): + def test_adds_without_duplicates(self): + data = {"permissions": {"allow": ["Read"]}} + steps = cfg.apply_rules(data, [("add", "allow", "Read"), + ("add", "allow", "Bash(ls)")]) + self.assertEqual(data["permissions"]["allow"], ["Read", "Bash(ls)"]) + self.assertEqual(steps, ["allow Bash(ls)"]) + + def test_a_rule_lives_in_one_list(self): + data = {"permissions": {"allow": ["WebFetch", "Read"]}} + steps = cfg.apply_rules(data, [("add", "deny", "WebFetch")]) + self.assertEqual(data["permissions"], {"allow": ["Read"], "deny": ["WebFetch"]}) + self.assertIn("WebFetch leaves allow", steps) + + def test_forget_drops_empty_lists_and_object(self): + data = {"model": "x", "permissions": {"ask": ["Edit"]}} + cfg.apply_rules(data, [("forget", "Edit")]) + self.assertEqual(data, {"model": "x"}) + + def test_keeps_unknown_keys(self): + data = {"permissions": {"defaultMode": "acceptEdits", "allow": ["A"]}} + cfg.apply_rules(data, [("forget", "A")]) + self.assertEqual(data, {"permissions": {"defaultMode": "acceptEdits"}}) + + def test_directories(self): + data = {"permissions": {"additionalDirectories": ["~/shared"]}} + home_shared = cfg.normalize_dir("~/shared") + steps = cfg.apply_rules(data, [("add-dir", "/data"), + ("remove-dir", home_shared)]) + self.assertEqual(data["permissions"]["additionalDirectories"], ["/data"]) + self.assertEqual(len(steps), 2) + + def test_nothing_to_do(self): + data = {} + self.assertEqual(cfg.apply_rules(data, [("forget", "X")]), []) + self.assertEqual(data, {}) + + +class TestRules(ConfigCase): + def test_accepts_the_usual_shapes(self): + for r in ("WebFetch", "Bash(npm test:*)", "Read(./.env)", + "mcp__github__create_issue", "WebFetch(domain:example.com)"): + self.assertEqual(cfg.check_rule(r), r) + + def test_rejects_junk(self): + for r in ("", "Bash(foo", "(x)", "rm -rf /"): + with self.assertRaises(SessionError): + cfg.check_rule(r) + + +class TestFiles(ConfigCase): + def test_keeps_mode_and_missing_newline(self): + self.write(self.state, {"oauthAccount": {"a": 1}, "projects": {}}, newline=False) + os.chmod(self.state, 0o600) + cfg.set_trust(self.proj, True) + with open(self.state, encoding="utf-8") as fh: + text = fh.read() + self.assertFalse(text.endswith("\n")) + self.assertEqual(stat.S_IMODE(os.stat(self.state).st_mode), 0o600) + data = json.loads(text) + self.assertEqual(data["oauthAccount"], {"a": 1}) + self.assertTrue(data["projects"][self.proj]["hasTrustDialogAccepted"]) + + def test_broken_json_is_not_overwritten(self): + os.makedirs(os.path.dirname(self.local())) + with open(self.local(), "w") as fh: + fh.write("{ nope") + with self.assertRaises(SessionError): + cfg.edit_settings(self.local(), [("add", "allow", "Read")]) + with open(self.local()) as fh: + self.assertEqual(fh.read(), "{ nope") + + def test_no_temporary_files_left(self): + cfg.edit_settings(self.local(), [("add", "allow", "Read")]) + self.assertEqual(os.listdir(os.path.dirname(self.local())), + ["settings.local.json"]) + + +class TestTrust(ConfigCase): + def test_trust_keeps_the_rest_of_the_entry(self): + self.write(self.state, {"projects": {self.proj: { + "allowedTools": [], "hasTrustDialogAccepted": False}}}) + self.assertTrue(cfg.set_trust(self.proj, True)) + self.assertEqual(self.read(self.state)["projects"][self.proj], + {"allowedTools": [], "hasTrustDialogAccepted": True}) + self.assertFalse(cfg.set_trust(self.proj, True)) + + def test_untrust_of_unknown_project_writes_nothing(self): + self.assertFalse(cfg.set_trust(self.proj, False)) + self.assertFalse(os.path.exists(self.state)) + + def test_dry_run_writes_nothing(self): + self.write(self.state, {"projects": {}}) + self.assertTrue(cfg.set_trust(self.proj, True, dry_run=True)) + self.assertEqual(self.read(self.state), {"projects": {}}) + + def test_trusted_parent(self): + trust = {"/a": True, "/a/b": False} + self.assertEqual(cfg.trusted_parent("/a/b/c", trust), "/a") + self.assertIsNone(cfg.trusted_parent("/z", trust)) + + +class TestResolveProject(ConfigCase): + def test_existing_directory(self): + self.assertEqual(cfg.resolve_project(self.proj + "/", set()), self.proj) + + def test_unique_known_project(self): + self.assertEqual(cfg.resolve_project("bar", {"/gone/foobar", "/x"}), + "/gone/foobar") + + def test_ambiguous_or_unknown(self): + with self.assertRaises(SessionError): + cfg.resolve_project("o", {"/foo", "/boo"}) + with self.assertRaises(SessionError): + cfg.resolve_project("nothing-like-it", {"/foo"}) + + +class TestCli(ConfigCase): + def test_allow_goes_to_local_settings_of_the_project(self): + code, out, _ = self.run_cli("--allow", "Bash(make:*)", "Read", "-p", self.proj) + self.assertEqual(code, 0) + self.assertEqual(self.read(self.local()), + {"permissions": {"allow": ["Bash(make:*)", "Read"]}}) + self.assertIn("allow Bash(make:*)", out) + + def test_without_project_goes_to_user_settings(self): + self.write(os.path.join(self.claude, "settings.json"), {"theme": "dark"}) + self.run_cli("--deny", "WebFetch") + self.assertEqual(self.read(os.path.join(self.claude, "settings.json")), + {"theme": "dark", "permissions": {"deny": ["WebFetch"]}}) + + def test_project_scope(self): + self.run_cli("--ask", "Edit", "--scope", "project", "-p", self.proj) + self.assertEqual( + self.read(os.path.join(self.proj, ".claude", "settings.json")), + {"permissions": {"ask": ["Edit"]}}) + + def test_project_scope_without_project_fails(self): + code, _, err = self.run_cli("--ask", "Edit", "--scope", "local") + self.assertEqual(code, 2) + self.assertIn("needs a project", err) + + def test_dirs_and_remove_rule(self): + self.run_cli("--allow", "Read", "--add-dir", self.home, "-p", self.proj) + self.run_cli("--remove-rule", "Read", "--remove-dir", self.home, "-p", self.proj) + self.assertEqual(self.read(self.local()), {}) + + def test_dry_run_touches_nothing(self): + code, out, _ = self.run_cli("--allow", "Read", "--trust", "-p", self.proj, + "--dry-run") + self.assertEqual(code, 0) + self.assertIn("nothing was touched", out) + self.assertFalse(os.path.exists(self.local())) + self.assertFalse(os.path.exists(self.state)) + + def test_trust_and_untrust(self): + self.write(self.state, {"numStartups": 3}) + self.run_cli("--trust", "-p", self.proj) + self.assertTrue(self.read(self.state)["projects"][self.proj][cfg.TRUST_KEY]) + _, out, _ = self.run_cli("--trust", "-p", self.proj) + self.assertIn("already trusted", out) + self.run_cli("--untrust", "-p", self.proj) + state = self.read(self.state) + self.assertFalse(state["projects"][self.proj][cfg.TRUST_KEY]) + self.assertEqual(state["numStartups"], 3) + + def test_trust_needs_a_project(self): + code, _, err = self.run_cli("--trust") + self.assertEqual(code, 2) + self.assertIn("need a project", err) + + def test_bad_rule(self): + code, _, err = self.run_cli("--allow", "Bash(oops", "-p", self.proj) + self.assertEqual(code, 2) + self.assertIn("does not look like a rule", err) + + def test_listing(self): + simple_tree(self.root) + self.write(self.local(), {"permissions": {"allow": ["Bash(make:*)"], + "additionalDirectories": ["/data"]}}) + self.write(self.state, {"projects": {self.proj: {cfg.TRUST_KEY: True}, + "/home/u/proj": {cfg.TRUST_KEY: False}}}) + code, out, _ = self.run_cli("-P") + self.assertEqual(code, 0) + self.assertIn("Bash(make:*)", out) + self.assertIn("/data", out) + self.assertIn("trusted", out) + self.assertNotIn("/home/u/proj", out) # no rules: hidden + self.assertIn("1 of 3 projects trusted", out) + + _, out, _ = self.run_cli("-P", "-p", "/home/u/proj") + self.assertIn("/home/u/proj not trusted", out) + + def test_listing_works_without_sessions(self): + os.rmdir(self.root) + code, out, _ = self.run_cli("-P") + self.assertEqual(code, 0) + self.assertIn("no rules", out) -- cgit v1.2.3