diff options
| author | Elvis Claros Castro <elvis@claros.ar> | 2026-10-03 12:05:23 -0300 |
|---|---|---|
| committer | Elvis Claros Castro <elvis@claros.ar> | 2026-10-03 12:05:23 -0300 |
| commit | 471e20a03503d3951a6fe12c1f3a354043a42e05 (patch) | |
| tree | 1f9021f803d24cca19b694bab001492c3918565c /claude_logbook | |
| parent | d3d0416b45698b9d40700b2196400542dc77c9ce (diff) | |
| download | claude-logbook-471e20a03503d3951a6fe12c1f3a354043a42e05.tar.gz claude-logbook-471e20a03503d3951a6fe12c1f3a354043a42e05.zip | |
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.
Diffstat (limited to 'claude_logbook')
| -rw-r--r-- | claude_logbook/__init__.py | 2 | ||||
| -rw-r--r-- | claude_logbook/cli.py | 142 | ||||
| -rw-r--r-- | claude_logbook/config.py | 314 | ||||
| -rw-r--r-- | claude_logbook/terminal.py | 58 |
4 files changed, 513 insertions, 3 deletions
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 + <project>/.claude/settings.json project scope, usually committed + <project>/.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 |