diff options
| author | Elvis Claros Castro <elvis@claros.ar> | 2026-10-03 19:03:27 -0300 |
|---|---|---|
| committer | Elvis Claros Castro <elvis@claros.ar> | 2026-10-03 19:03:27 -0300 |
| commit | 60c586001cf4d21ef1351be8c8ad7a269a6f005a (patch) | |
| tree | c3fd1685968c4b3835b8755e73412eeef286dfab | |
| parent | 2f8bc985b79e036ca6d34bb680a8858154c17a3b (diff) | |
| download | claude-logbook-60c586001cf4d21ef1351be8c8ad7a269a6f005a.tar.gz claude-logbook-60c586001cf4d21ef1351be8c8ad7a269a6f005a.zip | |
Share one session through a public link
claude-logbook -s REF --share uploads a session to a share server and
prints its link; --shares lists them, --unshare deletes them, --expire
picks how long they live. Before uploading it shows what goes up and warns
about anything that looks like a credential.
server/ is that share server: Go, standard library only, a FROM scratch
image. It serves /share/<id> as a page, .txt and .json, accepts only the
JSON payload (never HTML), pins the template's scripts with a CSP, keeps
secrets hashed and rate-limits per client IP.
| -rw-r--r-- | .dockerignore | 4 | ||||
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | Dockerfile | 18 | ||||
| -rw-r--r-- | README.es.md | 50 | ||||
| -rw-r--r-- | README.md | 49 | ||||
| -rw-r--r-- | claude_logbook/__init__.py | 2 | ||||
| -rw-r--r-- | claude_logbook/cli.py | 101 | ||||
| -rw-r--r-- | claude_logbook/config.py | 8 | ||||
| -rw-r--r-- | claude_logbook/share.py | 211 | ||||
| -rw-r--r-- | server/.gitignore | 1 | ||||
| -rw-r--r-- | server/README.md | 115 | ||||
| -rw-r--r-- | server/go.mod | 3 | ||||
| -rw-r--r-- | server/home.html | 101 | ||||
| -rw-r--r-- | server/limit.go | 127 | ||||
| -rw-r--r-- | server/main.go | 431 | ||||
| -rw-r--r-- | server/render.go | 206 | ||||
| -rw-r--r-- | server/server_test.go | 269 | ||||
| -rw-r--r-- | server/store.go | 265 | ||||
| -rw-r--r-- | tests/test_share.py | 228 |
19 files changed, 2185 insertions, 5 deletions
diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..bafe3e8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +* +!server/ +!claude_logbook/template.html +server/template.html @@ -5,6 +5,7 @@ sesiones.html data.json *.html !claude_logbook/template.html +!server/home.html # Python __pycache__/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5e9048b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +# Share server for claude-logbook (see server/README.md). +# Built from the repo root: it embeds claude_logbook/template.html. +FROM golang:1.23-alpine AS build +WORKDIR /src +COPY server/ ./ +COPY claude_logbook/template.html ./template.html +RUN CGO_ENABLED=0 go test ./... \ + && CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server . \ + && mkdir -p /out/data + +FROM scratch +COPY --from=build /out/server /server +COPY --from=build --chown=65534:65534 /out/data /data +USER 65534:65534 +EXPOSE 8181 +VOLUME /data +HEALTHCHECK --interval=30s --timeout=5s CMD ["/server", "-healthcheck"] +ENTRYPOINT ["/server"] diff --git a/README.es.md b/README.es.md index 73923f8..17c372d 100644 --- a/README.es.md +++ b/README.es.md @@ -29,6 +29,9 @@ sale es una copia legible de todo lo que escribiste alguna vez en Claude Code. Exportar una sola sesión (`-s 3 --html`) sigue siendo esa conversación entera: leela antes de compartirla. +`--share` sube una conversación a propósito, a un link público: ver +[Compartir una sesión](#compartir-una-sesión). + No lo commitees, no lo subas, no lo pegues en un issue. El `.gitignore` del repo ya excluye `sessions.html` y `data.json`, pero el archivo lo cuidás vos. @@ -102,6 +105,11 @@ claude-logbook docker -s 2 # lee el 2º de esos tres | `--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`. | +| `--share` | Con `-s`: publica esa sesión e imprime su link (pregunta antes, salvo `-y`). | +| `--expire TTL` | Cuánto vive el share: `1d`, `7d`, `30d` (default) o `90d`. | +| `--shares` | Lista lo que compartió esta máquina. | +| `--unshare REF` | Borra un share: su id, su URL o el prefijo de UUID de la sesión. | +| `--server URL` | Servidor de shares (default `$CLAUDE_LOGBOOK_SERVER` o `https://claude-logbook.all.ar`). | ### Borrar sesiones @@ -208,6 +216,46 @@ Las sesiones ya abiertas pueden necesitar reiniciarse para notarlo. marcha, que lo reescriben seguido: claude-logbook lo lee justo antes de cambiarlo y reintenta si se modificó en el medio. +## Compartir una sesión + +`--share` publica **una** sesión en <https://claude-logbook.all.ar> e imprime +su link: + +```bash +claude-logbook -s 3 --share # muestra qué se sube y pregunta +claude-logbook -s 3 --share --expire 7d # desaparece en una semana (default 30 días) +claude-logbook -s 3 --share # otra vez más tarde: mismo link, contenido nuevo +claude-logbook --shares # qué compartiste y hasta cuándo +claude-logbook --unshare 5d10f1ee # bajarlo (id, URL o sesión) +``` + +Cada share tiene tres formas: + +| URL | Contenido | +| --- | --- | +| `/share/<id>` | La conversación como página, la misma vista que `--html`. | +| `/share/<id>.txt` | La transcripción en texto plano. | +| `/share/<id>.json` | Los datos, como los imprime `--json -s`. | + +Antes de subir muestra el título, la ruta del proyecto, el tamaño y un aviso +por cualquier cosa que parezca una API key, un token o una clave privada (dónde +está, nunca el valor). `--dry-run` se detiene ahí. + +Para tener en cuenta: + +- **Cualquiera con el link puede leer la conversación entera**, llamadas a + herramientas y rutas incluidas. No está cifrada; el servidor también la puede + leer. +- Solo la máquina que creó un share puede actualizarlo o borrarlo: el servidor + devuelve un secret que se guarda en + `$XDG_STATE_HOME/claude-logbook/shares.json` (`~/.local/state/...`), con modo + 600. Si perdés ese archivo, el share queda hasta que vence. +- Las memorias nunca se comparten. + +El servidor está en [`server/`](server/README.md): Go, solo biblioteca estándar, +imagen Docker `FROM scratch`. Podés correr el tuyo y apuntar +`CLAUDE_LOGBOOK_SERVER` a él. + ## La página HTML `claude-logbook --html` genera un único archivo con los datos adentro. Sin @@ -329,7 +377,9 @@ tocan `~/.claude`. No hay nada que instalar: ni runner de tests ni dependencias. | `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/share.py` | Hablar con el servidor de shares y el registro local de shares. | | `claude_logbook/cli.py` | Los argumentos y los comandos. | +| `server/` | El servidor de shares (Go): `cd server && go generate && go test ./...`. | | `claude_logbook/template.html` | La página: marcado, estilos y el código del navegador. | ## Licencia @@ -28,6 +28,9 @@ readable copy of everything you ever typed into Claude Code. Exporting a single session (`-s 3 --html`) is still that whole conversation: read it before you share it. +`--share` uploads one conversation on purpose, to a public link: see +[Sharing a session](#sharing-a-session). + Do not commit it, do not upload it, do not paste it into a bug report. The repository's `.gitignore` already excludes `sessions.html` and `data.json`, but the file itself is yours to look after. @@ -102,6 +105,11 @@ claude-logbook docker -s 2 # reads the 2nd of those three | `--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`. | +| `--share` | With `-s`: publish that session and print its link (asks first unless `-y`). | +| `--expire TTL` | How long the share lives: `1d`, `7d`, `30d` (default) or `90d`. | +| `--shares` | List what this machine has shared. | +| `--unshare REF` | Delete a share: its id, its URL or the session UUID prefix. | +| `--server URL` | Share server (default `$CLAUDE_LOGBOOK_SERVER` or `https://claude-logbook.all.ar`). | ### Deleting sessions @@ -207,6 +215,45 @@ notice. Code, which rewrite it often: claude-logbook reads it right before changing it, and retries if it moves in between. +## Sharing a session + +`--share` publishes **one** session on <https://claude-logbook.all.ar> and +prints its link: + +```bash +claude-logbook -s 3 --share # shows what goes up and asks +claude-logbook -s 3 --share --expire 7d # gone in a week (default 30 days) +claude-logbook -s 3 --share # again later: same link, new content +claude-logbook --shares # what you have shared, and until when +claude-logbook --unshare 5d10f1ee # take it down (id, URL or session) +``` + +Each share has three forms: + +| URL | Content | +| --- | --- | +| `/share/<id>` | The conversation as a page, the same view as `--html`. | +| `/share/<id>.txt` | Plain text transcript. | +| `/share/<id>.json` | The data, as `--json -s` prints it. | + +Before uploading it shows the title, the project path, the size and a warning +for anything that looks like an API key, a token or a private key (where it +is, never the value). `--dry-run` stops there. + +What to keep in mind: + +- **Anyone with the link can read the whole conversation**, tool calls and + paths included. It is not encrypted; the server can read it too. +- Only the machine that created a share can update or delete it: the server + returns a secret that is kept in + `$XDG_STATE_HOME/claude-logbook/shares.json` (`~/.local/state/...`), mode + 600. Lose that file and the share stays until it expires. +- Memories are never shared. + +The server lives in [`server/`](server/README.md): Go, standard library only, +a `FROM scratch` Docker image. You can run your own and point +`CLAUDE_LOGBOOK_SERVER` at it. + ## The HTML page `claude-logbook --html` produces one file with the data embedded inside it. No @@ -328,7 +375,9 @@ The tests build fake `.jsonl` trees in a temporary directory and never touch | `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/share.py` | Talking to the share server and the local registry of shares. | | `claude_logbook/cli.py` | Argument parsing and the commands. | +| `server/` | The share server (Go): `cd server && go generate && go test ./...`. | | `claude_logbook/template.html` | The page: markup, styles and the browser-side code. | ## License 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 diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..93598e4 --- /dev/null +++ b/server/.gitignore @@ -0,0 +1 @@ +template.html diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..8e2de37 --- /dev/null +++ b/server/README.md @@ -0,0 +1,115 @@ +# claude-logbook share server + +Serves the sessions published with `claude-logbook -s REF --share`: + +| Route | | +| --- | --- | +| `GET /` | Home with the instructions. | +| `GET /share/<id>` | The conversation as a page (the CLI's `template.html`). | +| `GET /share/<id>.txt` | Plain text transcript. | +| `GET /share/<id>.json` | The stored payload. | +| `POST /api/shares` | `{"payload": {...}, "expire": "30d"}` → `201 {id, url, secret, expires}` | +| `PUT /api/shares/<id>` | `Authorization: Bearer <secret>`; replaces the payload. | +| `DELETE /api/shares/<id>` | `Authorization: Bearer <secret>`. | +| `GET /healthz` | `ok`. | + +Anyone can create a share; only the holder of the secret returned on +creation can replace or delete it. The server keeps only the secret's SHA-256. + +## Security model + +- **No HTML is accepted.** The payload is the JSON of `claude-logbook --json -s`; + it is checked field by field, unknown keys are dropped, memories are refused, + and the page is built from the template embedded in the binary. +- The data goes inside `<script type="application/json">` with `<`, `>` and `&` + escaped, and the page is served with a CSP that allows only the template's + two inline scripts by hash: no inline handlers, no external anything. +- Share ids are 10 base62 characters from `crypto/rand`; pages carry + `X-Robots-Tag: noindex` and `Referrer-Policy: no-referrer`. +- Limits: request body (`MAX_BYTES`), sessions per share (`MAX_SESSIONS`), + and a token bucket per client IP for creations and for updates/deletes. +- `X-Forwarded-For` is believed only when the connection comes from + `TRUSTED_PROXY`; otherwise the peer address counts. +- Logs carry method, path, status and size, never bodies or headers. + +Content is **not encrypted**: whoever runs the server can read the shares. + +## Configuration + +| Env | Flag | Default | +| --- | --- | --- | +| `ADDR` | `-addr` | `:8181` | +| `DATA_DIR` | `-data` | `/data` | +| `PUBLIC_URL` | `-public-url` | `https://claude-logbook.all.ar` | +| `MAX_BYTES` | `-max-bytes` | `10485760` (10 MB) | +| `MAX_SESSIONS` | `-max-sessions` | `1` | +| `TRUSTED_PROXY` | `-trusted-proxy` | empty: trust no proxy (IPs or CIDRs, comma separated) | +| `CREATES_PER_HOUR` | `-creates-per-hour` | `10` per IP | +| `WRITES_PER_HOUR` | `-writes-per-hour` | `60` per IP | + +Shares expire after `1d`, `7d`, `30d` (default) or `90d`. Expired ones return +404 at once and are deleted by a sweep every hour. + +Storage is two files per share in `DATA_DIR` (`<id>.json`, `<id>.meta`), mode +600, written atomically. Back up that directory and you have backed up +everything. + +## Build and run + +The image is built from the **repository root**, because it embeds +`claude_logbook/template.html`: + +```bash +docker build -t claude-logbook-server . +docker run -d --name claude-logbook-server --restart unless-stopped \ + -p 8181:8181 -v claude-logbook-data:/data \ + -e TRUSTED_PROXY=203.0.113.10 \ + claude-logbook-server +``` + +or with compose: + +```yaml +services: + claude-logbook: + build: . + image: claude-logbook-server + restart: unless-stopped + ports: ["8181:8181"] # 127.0.0.1:8181:8181 if NPM runs on this same host + volumes: ["claude-logbook-data:/data"] + environment: + TRUSTED_PROXY: 203.0.113.10 # the address NPM connects from +volumes: + claude-logbook-data: +``` + +The image is `FROM scratch`: one static binary, running as `65534:65534`, +with a `HEALTHCHECK` that runs `/server -healthcheck`. + +### Nginx Proxy Manager + +Add a proxy host `claude-logbook.all.ar` → `<host>:8181`, with an SSL +certificate (Let's Encrypt) and *Force SSL*. Add this under *Advanced* so +uploads up to `MAX_BYTES` get through: + +```nginx +client_max_body_size 10m; +``` + +`TRUSTED_PROXY` must be the address the connections from NPM arrive from. +With NPM on another machine, that is its public IP (`203.0.113.10` above is +only an example), and the firewall should open 8181 to that IP only. If NPM +runs in Docker on the same host, it is its address on the Docker network +(e.g. `172.17.0.0/16`) instead. If it is wrong, every visitor +seems to come from NPM, they all share one rate-limit bucket, and ten shares +an hour from anyone block everyone. + +## Development + +```bash +cd server +go generate # copies ../claude_logbook/template.html (git-ignored) +go vet ./... && go test ./... +go run . -data /tmp/shares -public-url http://localhost:8181 +CLAUDE_LOGBOOK_SERVER=http://localhost:8181 claude-logbook -s 3 --share +``` diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..058d8b7 --- /dev/null +++ b/server/go.mod @@ -0,0 +1,3 @@ +module claude-logbook/server + +go 1.23 diff --git a/server/home.html b/server/home.html new file mode 100644 index 0000000..6ae6ad1 --- /dev/null +++ b/server/home.html @@ -0,0 +1,101 @@ +<!doctype html> +<html lang="en"> +<head> +<meta charset="utf-8"> +<meta name="viewport" content="width=device-width, initial-scale=1"> +<meta name="color-scheme" content="light dark"> +<title>claude-logbook</title> +<meta name="description" content="Browse, export and share your Claude Code sessions from the terminal."> +<style> + :root { + --bg: #faf8f4; --fg: #22201c; --muted: #6b665c; --line: #e4dfd5; + --code-bg: #f0ece4; --accent: #b4532a; + } + @media (prefers-color-scheme: dark) { + :root { + --bg: #1a1917; --fg: #ece8e1; --muted: #a29c90; --line: #34312c; + --code-bg: #262420; --accent: #e08a5c; + } + } + * { box-sizing: border-box; } + body { + margin: 0; background: var(--bg); color: var(--fg); + font: 16px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif; + } + main { max-width: 760px; margin: 0 auto; padding: 48px 16px 64px; } + h1 { font-size: 2rem; margin: 0 0 4px; letter-spacing: -0.02em; } + h1 span { color: var(--accent); } + h2 { font-size: 1.15rem; margin: 40px 0 8px; } + p.lead { color: var(--muted); margin: 0 0 24px; font-size: 1.1rem; } + pre, code { font: 14px/1.5 ui-monospace, "SF Mono", Menlo, Consolas, |