aboutsummaryrefslogtreecommitdiffstats
path: root/claude_logbook
diff options
context:
space:
mode:
Diffstat (limited to 'claude_logbook')
-rw-r--r--claude_logbook/__init__.py2
-rw-r--r--claude_logbook/cli.py101
-rw-r--r--claude_logbook/config.py8
-rw-r--r--claude_logbook/share.py211
4 files changed, 317 insertions, 5 deletions
diff --git a/claude_logbook/__init__.py b/claude_logbook/__init__.py
index f7d4458..b05f474 100644
--- a/claude_logbook/__init__.py
+++ b/claude_logbook/__init__.py
@@ -3,6 +3,6 @@
No dependencies: standard library only.
"""
-__version__ = "1.4.0"
+__version__ = "1.5.0"
__all__ = ["__version__"]
diff --git a/claude_logbook/cli.py b/claude_logbook/cli.py
index f90ac26..57385c1 100644
--- a/claude_logbook/cli.py
+++ b/claude_logbook/cli.py
@@ -20,6 +20,7 @@ from .terminal import (
)
from . import config as cfg
from . import memory as mem
+from . import share
from . import webpage
DEFAULT_HTML = "sessions.html"
@@ -72,6 +73,12 @@ user settings unless -p names a project, then to its settings.local.json;
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
+
+sharing (one session, readable by anyone with the link; asks first unless -y):
+ claude-logbook -s 3 --share upload #3, prints its link
+ claude-logbook -s 3 --share --expire 7d gone in a week (default 30d)
+ claude-logbook --shares what this machine has shared
+ claude-logbook --unshare 5d10f1ee delete it (share id, URL or session)
"""
@@ -143,13 +150,26 @@ def build_parser():
output_path.add_argument("--open", action="store_true",
help="open what --html writes in the browser")
+ sharing = ap.add_argument_group("share")
+ sharing.add_argument("--share", action="store_true",
+ help="publish the -s session and print its link")
+ sharing.add_argument("--expire", choices=share.EXPIRES, default=share.DEFAULT_EXPIRE,
+ help=f"how long the share lives (default {share.DEFAULT_EXPIRE})")
+ sharing.add_argument("--shares", action="store_true",
+ help="list what this machine has shared")
+ sharing.add_argument("--unshare", metavar="REF",
+ help="delete a share: its id, its URL or the session UUID prefix")
+ sharing.add_argument("--server", metavar="URL",
+ help=f"share server (default ${share.SERVER_ENV} or "
+ f"{share.DEFAULT_SERVER})")
+
delete_items = ap.add_argument_group("delete")
delete_items.add_argument("-D", "--delete", metavar="REF", nargs="+",
help="delete those sessions (index or UUID prefix)")
delete_items.add_argument("--delete-empty", action="store_true",
help="delete every session with no messages")
delete_items.add_argument("-y", "--yes", action="store_true",
- help="do not ask before deleting")
+ help="do not ask before deleting or sharing")
delete_items.add_argument("--dry-run", action="store_true",
help="show what would change and touch nothing")
@@ -567,7 +587,83 @@ def run_perms(args, st):
return cmd_perms_list(sessions, args, st)
+# ──────────────────────────────── sharing ─────────────────────────────────
+
+def cmd_share(sessions, args, st):
+ import json
+ if not args.show:
+ raise SessionError("--share needs a session (-s REF): one at a time")
+ s = pick(filtered(sessions, args), args.show)
+ if s["e"]:
+ raise SessionError("that session has no messages, there is nothing to share")
+ server = share.server_url(args.server)
+ payload = webpage.build_payload(public_records([s]), [])
+ size = len(json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode())
+ old = share.entry_for_session(share.load_registry(), s["id"], server)
+
+ err = sys.stderr
+ print(f"{st.bold}{s['t'] or 'Untitled session'}{st.reset}", file=err)
+ print(f" {short_home(s['p'])} · {s['u']} yours / {s['a']} from Claude · "
+ f"{len(s['c'])} blocks · {fmt_size(size / 1024)}", file=err)
+ where = f"updates {old['url']}" if old else f"new link on {server}"
+ print(f" {where}, expires in {args.expire}", file=err)
+ for kind, blocks in share.scan_secrets(payload):
+ places = ["the title" if b == 0 else f"block {b}" for b in blocks[:8]]
+ shown = ", ".join(places) + (" …" if len(blocks) > 8 else "")
+ print(f" {st.copper}warning:{st.reset} possible {kind} in {shown} "
+ f"(see it with -s {args.show})", file=err)
+ print(f"{st.faint} Anyone with the link can read the whole conversation, "
+ f"tool calls and paths included.{st.reset}", file=err)
+
+ if args.dry_run:
+ print("--dry-run: nothing was uploaded.", file=err)
+ return 0
+ if not args.yes and not confirm("Upload it? [y/N] "):
+ print("Nothing was uploaded.", file=err)
+ return 1
+
+ entry, created = share.publish(server, payload, args.expire, s["id"], s["t"])
+ print(f"{'Shared' if created else 'Updated'} · expires {fmt_expiry(entry)}", file=err)
+ print(entry["url"])
+ print(f"{st.faint} {entry['url']}.txt · {entry['url']}.json{st.reset}", file=err)
+ return 0
+
+
+def fmt_expiry(entry):
+ exp = entry.get("expires") or "?"
+ return exp[:16].replace("T", " ") + " UTC" if len(exp) >= 16 else exp
+
+
+def run_shares(args, st):
+ entries = share.load_registry()
+ if args.unshare:
+ entry = share.find_entry(entries, args.unshare)
+ if args.dry_run:
+ print(f"--dry-run: would delete {entry['url']}", file=sys.stderr)
+ return 0
+ if share.unpublish(entry):
+ print(f"Deleted {entry['url']}")
+ else:
+ print(f"{entry['url']} was already gone; forgotten here too.")
+ return 0
+
+ if not entries:
+ print("Nothing shared from this machine yet.", file=sys.stderr)
+ return 0
+ for e in sorted(entries, key=lambda e: e.get("expires") or ""):
+ state = (f"{st.copper}expired{st.reset}" if share.is_expired(e)
+ else f"{st.faint}until {fmt_expiry(e)}{st.reset}")
+ print(f"{st.bold}{clip(e.get('title') or 'Untitled session', 60)}{st.reset} {state}")
+ print(f" {e['url']} {st.faint}session {(e.get('session') or '?')[:8]}{st.reset}")
+ print(f"\n{plural(len(entries), 'share', 'shares')} · "
+ f"secrets in {short_home(share.registry_path())}")
+ return 0
+
+
def run(args):
+ if args.shares or args.unshare:
+ return run_shares(args, Style.from_stream(sys.stdout, args.no_color))
+
if wants_perms(args):
return run_perms(args, Style.from_stream(sys.stdout, args.no_color))
@@ -587,6 +683,9 @@ def run(args):
if args.memory:
return run_memory(sessions, args, st)
+ if args.share:
+ return cmd_share(sessions, args, st)
+
if args.json or args.html is not None:
chosen, memories = export_selection(sessions, args)
if not chosen:
diff --git a/claude_logbook/config.py b/claude_logbook/config.py
index 96c2e48..cd30675 100644
--- a/claude_logbook/config.py
+++ b/claude_logbook/config.py
@@ -82,9 +82,11 @@ def read_json(path):
return data
-def write_json(path, data):
+def write_json(path, data, mode=None):
"""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."""
+ whether it ended in a newline, so an untouched key reads exactly the same.
+ An explicit `mode` wins over both, for files that hold secrets."""
+ forced = mode
try:
mode = os.stat(path).st_mode & 0o777
with open(path, "rb") as fh:
@@ -107,7 +109,7 @@ def write_json(path, data):
json.dump(data, fh, indent=2, ensure_ascii=False)
if newline:
fh.write("\n")
- os.chmod(tmp, mode)
+ os.chmod(tmp, forced if forced is not None else mode)
os.replace(tmp, path)
except BaseException:
try:
diff --git a/claude_logbook/share.py b/claude_logbook/share.py
new file mode 100644
index 0000000..77f517a
--- /dev/null
+++ b/claude_logbook/share.py
@@ -0,0 +1,211 @@
+"""Publishing one session on a share server (claude-logbook.all.ar by default).
+
+The server takes the same JSON `--json -s` prints and serves it at
+/share/<id> (page), /share/<id>.txt and /share/<id>.json. Creating a share
+returns a secret; only with it can the share be replaced or deleted, so it is
+kept in a local registry readable by its owner alone:
+
+ $XDG_STATE_HOME/claude-logbook/shares.json (~/.local/state/... by default)
+
+Only the standard library: urllib for HTTP.
+"""
+
+import json
+import os
+import re
+import urllib.error
+import urllib.request
+from datetime import datetime, timezone
+
+from . import __version__
+from .config import read_json, write_json
+from .sessions import SessionError
+
+DEFAULT_SERVER = "https://claude-logbook.all.ar"
+SERVER_ENV = "CLAUDE_LOGBOOK_SERVER"
+EXPIRES = ("1d", "7d", "30d", "90d")
+DEFAULT_EXPIRE = "30d"
+TIMEOUT = 60
+
+# Things that should not leave the machine by accident. Only the kind and
+# where it is are reported, never the match itself.
+SECRET_PATTERNS = (
+ ("Anthropic API key", re.compile(r"sk-ant-[A-Za-z0-9_-]{20,}")),
+ ("OpenAI-style API key", re.compile(r"\bsk-(?!ant-)(?:proj-)?[A-Za-z0-9_-]{20,}")),
+ ("GitHub token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_\w{20,})")),
+ ("AWS access key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
+ ("private key", re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----")),
+ ("Slack token", re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}")),
+ ("password or token assignment", re.compile(
+ r"(?i)\b(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*['\"]?[^\s'\"]{8,}")),
+)
+
+
+class NotFound(SessionError):
+ """The server no longer has that share (expired or deleted)."""
+
+
+# ──────────────────────────────── local registry ─────────────────────────
+
+def server_url(arg=None):
+ return (arg or os.environ.get(SERVER_ENV) or DEFAULT_SERVER).rstrip("/")
+
+
+def registry_path():
+ base = os.environ.get("XDG_STATE_HOME") or os.path.join(
+ os.path.expanduser("~"), ".local", "state")
+ return os.path.join(base, "claude-logbook", "shares.json")
+
+
+def load_registry():
+ shares = read_json(registry_path()).get("shares")
+ return [e for e in shares if isinstance(e, dict)] if isinstance(shares, list) else []
+
+
+def save_registry(entries):
+ path = registry_path()
+ os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True)
+ write_json(path, {"shares": entries}, mode=0o600)
+
+
+def entry_for_session(entries, session_id, server):
+ for e in entries:
+ if e.get("session") == session_id and e.get("server") == server:
+ return e
+ return None
+
+
+def find_entry(entries, ref):
+ """By share id, by its URL or by a prefix of the session UUID."""
+ ref = ref.strip().rstrip("/")
+ if "/share/" in ref:
+ ref = ref.rsplit("/share/", 1)[1].split(".")[0]
+ hits = [e for e in entries if e.get("id") == ref]
+ if not hits and len(ref) >= 4:
+ hits = [e for e in entries if (e.get("session") or "").startswith(ref.lower())]
+ if len(hits) == 1:
+ return hits[0]
+ if not hits:
+ raise SessionError(f"no share of yours matches '{ref}' (see --shares)")
+ raise SessionError(f"'{ref}' is ambiguous, it matches {len(hits)} shares")
+
+
+def is_expired(entry, now=None):
+ try:
+ exp = datetime.fromisoformat(entry["expires"].replace("Z", "+00:00"))
+ except (KeyError, AttributeError, ValueError):
+ return False
+ return exp <= (now or datetime.now(timezone.utc))
+
+
+# ──────────────────────────────── content check ──────────────────────────
+
+def scan_secrets(payload):
+ """[(kind, [block numbers])] for what looks like a credential. Block 0 is
+ the title; the rest count from 1 as the conversation goes."""
+ found = {}
+ for s in payload.get("s", ()):
+ texts = [(0, s.get("t") or "")] + [
+ (i, b.get("x") or "") for i, b in enumerate(s.get("c", ()), 1)]
+ for where, text in texts:
+ for kind, rx in SECRET_PATTERNS:
+ if rx.search(text):
+ found.setdefault(kind, []).append(where)
+ return [(kind, found[kind]) for kind, _ in SECRET_PATTERNS if kind in found]
+
+
+# ──────────────────────────────── http ───────────────────────────────────
+
+def _request(method, url, body=None, secret=None):
+ data = None if body is None else json.dumps(
+ body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+ req = urllib.request.Request(url, data=data, method=method, headers={
+ "User-Agent": f"claude-logbook/{__version__}",
+ "Accept": "application/json",
+ })
+ if data is not None:
+ req.add_header("Content-Type", "application/json")
+ if secret:
+ req.add_header("Authorization", f"Bearer {secret}")
+ try:
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
+ raw = resp.read()
+ except urllib.error.HTTPError as e:
+ raise _http_error(e)
+ except urllib.error.URLError as e:
+ raise SessionError(f"cannot reach {url.split('/api/')[0]}: {e.reason}")
+ except (TimeoutError, OSError) as e:
+ raise SessionError(f"cannot reach {url.split('/api/')[0]}: {e}")
+ return json.loads(raw) if raw.strip() else {}
+
+
+def _http_error(e):
+ try:
+ msg = json.loads(e.read() or b"{}").get("error") or e.reason
+ except (ValueError, AttributeError, OSError):
+ msg = e.reason
+ if e.code == 404:
+ return NotFound("the server no longer has that share (expired or deleted)")
+ if e.code == 413:
+ return SessionError(f"the session is too large for the server ({msg})")
+ if e.code == 429:
+ return SessionError("the server is limiting requests from your address; try again later")
+ if e.code == 403:
+ return SessionError("the server rejected the secret of that share")
+ return SessionError(f"the server answered {e.code}: {msg}")
+
+
+def create(server, payload, expire):
+ return _request("POST", f"{server}/api/shares",
+ {"payload": payload, "expire": expire})
+
+
+def update(server, entry, payload, expire):
+ return _request("PUT", f"{server}/api/shares/{entry['id']}",
+ {"payload": payload, "expire": expire}, secret=entry["secret"])
+
+
+def delete(server, entry):
+ _request("DELETE", f"{server}/api/shares/{entry['id']}", secret=entry["secret"])
+
+
+def publish(server, payload, expire, session, title):
+ """Creates the share, or updates the one this machine already made for
+ that session (the link stays the same). Returns (entry, created)."""
+ entries = load_registry()
+ old = entry_for_session(entries, session, server)
+ created = True
+ if old:
+ try:
+ resp = update(server, old, payload, expire)
+ resp["secret"] = old["secret"]
+ created = False
+ except NotFound:
+ resp = create(server, payload, expire)
+ entries.remove(old)
+ else:
+ resp = create(server, payload, expire)
+ entry = {
+ "id": resp["id"], "url": resp["url"], "secret": resp["secret"],
+ "server": server, "session": session, "title": title,
+ "created": (old or {}).get("created") if not created else
+ datetime.now(timezone.utc).isoformat(timespec="seconds"),
+ "expires": resp.get("expires"),
+ }
+ entries.append(entry)
+ save_registry(entries)
+ return entry, created
+
+
+def unpublish(entry):
+ """Deletes it on its server and forgets it. A share the server no longer
+ has is forgotten all the same. Returns False in that case."""
+ gone = True
+ try:
+ delete(entry["server"], entry)
+ except NotFound:
+ gone = False
+ entries = [e for e in load_registry()
+ if not (e.get("id") == entry["id"] and e.get("server") == entry["server"])]
+ save_registry(entries)
+ return gone