From 60c586001cf4d21ef1351be8c8ad7a269a6f005a Mon Sep 17 00:00:00 2001 From: Elvis Claros Castro Date: Sat, 3 Oct 2026 19:03:27 -0300 Subject: 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/ 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. --- .dockerignore | 4 + .gitignore | 1 + Dockerfile | 18 ++ README.es.md | 50 ++++++ README.md | 49 ++++++ claude_logbook/__init__.py | 2 +- claude_logbook/cli.py | 101 ++++++++++- claude_logbook/config.py | 8 +- claude_logbook/share.py | 211 ++++++++++++++++++++++ server/.gitignore | 1 + server/README.md | 115 ++++++++++++ server/go.mod | 3 + server/home.html | 101 +++++++++++ server/limit.go | 127 +++++++++++++ server/main.go | 431 +++++++++++++++++++++++++++++++++++++++++++++ server/render.go | 206 ++++++++++++++++++++++ server/server_test.go | 269 ++++++++++++++++++++++++++++ server/store.go | 265 ++++++++++++++++++++++++++++ tests/test_share.py | 228 ++++++++++++++++++++++++ 19 files changed, 2185 insertions(+), 5 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 claude_logbook/share.py create mode 100644 server/.gitignore create mode 100644 server/README.md create mode 100644 server/go.mod create mode 100644 server/home.html create mode 100644 server/limit.go create mode 100644 server/main.go create mode 100644 server/render.go create mode 100644 server/server_test.go create mode 100644 server/store.go create mode 100644 tests/test_share.py 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 diff --git a/.gitignore b/.gitignore index f5156d7..1ba18af 100644 --- a/.gitignore +++ b/.gitignore @@ -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 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/` | La conversación como página, la misma vista que `--html`. | +| `/share/.txt` | La transcripción en texto plano. | +| `/share/.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 diff --git a/README.md b/README.md index c41738a..4913fcf 100644 --- a/README.md +++ b/README.md @@ -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 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/` | The conversation as a page, the same view as `--html`. | +| `/share/.txt` | Plain text transcript. | +| `/share/.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/ (page), /share/.txt and /share/.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/` | The conversation as a page (the CLI's `template.html`). | +| `GET /share/.txt` | Plain text transcript. | +| `GET /share/.json` | The stored payload. | +| `POST /api/shares` | `{"payload": {...}, "expire": "30d"}` → `201 {id, url, secret, expires}` | +| `PUT /api/shares/` | `Authorization: Bearer `; replaces the payload. | +| `DELETE /api/shares/` | `Authorization: Bearer `. | +| `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 ``) + +// NewPage splits the template at its single marker and computes the CSP that +// allows exactly its inline scripts. +func NewPage(template string) (*Page, error) { + if n := strings.Count(template, dataMarker); n != 1 { + return nil, fmt.Errorf("template must contain exactly one %s (found %d)", dataMarker, n) + } + var hashes []string + for _, m := range scriptRE.FindAllStringSubmatch(template, -1) { + if strings.Contains(m[1], "application/json") { + continue // data, not code: CSP does not apply to it + } + sum := sha256.Sum256([]byte(m[2])) + hashes = append(hashes, "'sha256-"+base64.StdEncoding.EncodeToString(sum[:])+"'") + } + if len(hashes) == 0 { + return nil, errors.New("template has no scripts") + } + before, after, _ := strings.Cut(template, dataMarker) + csp := "default-src 'none'; script-src " + strings.Join(hashes, " ") + + "; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; " + + "form-action 'none'; frame-ancestors 'none'" + return &Page{before: before, after: after, csp: csp}, nil +} + +// EncodeData does what encode_payload in webpage.py does: the HTML parser +// ends a tag."}]}` + +func payload(sessions ...string) string { + if len(sessions) == 0 { + sessions = []string{session} + } + return `{"s":[` + strings.Join(sessions, ",") + `],"m":[]}` +} + +type harness struct { + t *testing.T + srv *Server + h http.Handler +} + +func newHarness(t *testing.T, mod func(*Config)) *harness { + t.Helper() + cfg := Config{Addr: ":0", DataDir: t.TempDir(), PublicURL: "https://x.test", + MaxBytes: 1 << 20, MaxSessions: 1, TrustedProxy: "10.0.0.1", + CreatesPerH: 100, WritesPerH: 100} + if mod != nil { + mod(&cfg) + } + srv, err := NewServer(cfg) + if err != nil { + t.Fatal(err) + } + return &harness{t: t, srv: srv, h: srv.Routes()} +} + +func (h *harness) do(method, path, body, secret string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.RemoteAddr = "192.0.2.1:1234" + if secret != "" { + req.Header.Set("Authorization", "Bearer "+secret) + } + rec := httptest.NewRecorder() + h.h.ServeHTTP(rec, req) + return rec +} + +func (h *harness) create(body string) shareResp { + h.t.Helper() + rec := h.do("POST", "/api/shares", body, "") + if rec.Code != http.StatusCreated { + h.t.Fatalf("create: %d %s", rec.Code, rec.Body) + } + var r shareResp + if err := json.Unmarshal(rec.Body.Bytes(), &r); err != nil { + h.t.Fatal(err) + } + return r +} + +func TestCreateAndRead(t *testing.T) { + h := newHarness(t, nil) + r := h.create(`{"payload":` + payload() + `,"expire":"7d"}`) + if !ValidID(r.ID) || r.Secret == "" || r.URL != "https://x.test/share/"+r.ID { + t.Fatalf("bad response %+v", r) + } + if d := time.Until(r.Expires); d < 6*24*time.Hour || d > 8*24*time.Hour { + t.Fatalf("expiry %v", r.Expires) + } + + page := h.do("GET", "/share/"+r.ID, "", "") + if page.Code != 200 || !strings.Contains(page.Header().Get("Content-Type"), "text/html") { + t.Fatalf("html: %d", page.Code) + } + csp := page.Header().Get("Content-Security-Policy") + if !strings.Contains(csp, "script-src 'sha256-") || strings.Contains(csp, "unsafe-inline' ;") { + t.Fatalf("csp: %s", csp) + } + if page.Header().Get("X-Robots-Tag") == "" { + t.Fatal("no X-Robots-Tag") + } + body := page.Body.String() + // The data block must hold exactly one : its own end. + start := strings.Index(body, `") + if strings.Contains(body[start:start+end], " tag." { + t.Fatalf("json roundtrip: %v %s", err, js.Body) + } + + if rec := h.do("GET", "/share/"+r.ID+".pdf", "", ""); rec.Code != 404 { + t.Fatalf("unknown extension: %d", rec.Code) + } +} + +func TestUpdateAndDeleteNeedTheSecret(t *testing.T) { + h := newHarness(t, nil) + r := h.create(`{"payload":` + payload() + `}`) + newer := str