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 /server | |
| 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.
Diffstat (limited to 'server')
| -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 |
9 files changed, 1518 insertions, 0 deletions
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, monospace; } + code { background: var(--code-bg); padding: 1px 5px; border-radius: 4px; } + pre { + background: var(--code-bg); padding: 14px 16px; border-radius: 8px; + overflow-x: auto; margin: 8px 0 16px; + } + pre code { background: none; padding: 0; } + .c { color: var(--muted); } + table { border-collapse: collapse; width: 100%; margin: 8px 0 16px; font-size: 15px; } + td { border-top: 1px solid var(--line); padding: 8px 8px 8px 0; vertical-align: top; } + td:first-child { white-space: nowrap; } + .note { + border-left: 3px solid var(--accent); padding: 4px 0 4px 14px; margin: 16px 0; + } + footer { margin-top: 48px; padding-top: 16px; border-top: 1px solid var(--line); + color: var(--muted); font-size: 14px; } + a { color: var(--accent); } +</style> +</head> +<body> +<main> + <h1>claude<span>-</span>logbook</h1> + <p class="lead">Browse, export and share your Claude Code sessions from the terminal.</p> + + <h2>Install</h2> +<pre><code>pipx install claude-logbook <span class="c"># or: pip install --user claude-logbook</span> +claude-logbook <span class="c"># table of every session</span></code></pre> + + <h2>Share a session</h2> + <p>Pick a session by its number in the table or by a prefix of its UUID, then share it:</p> +<pre><code>claude-logbook -s 3 --share <span class="c"># asks before uploading</span> +claude-logbook -s 5d10f1ee --share --expire 7d +claude-logbook --shares <span class="c"># what you have shared</span> +claude-logbook --unshare 5d10f1ee <span class="c"># take it down</span></code></pre> + <p>Sharing the same session again updates it in place: the link stays the same.</p> + + <h2>Links</h2> + <table> + <tr><td><code>{{PUBLIC_URL}}/share/<id></code></td><td>the conversation as a page</td></tr> + <tr><td><code>{{PUBLIC_URL}}/share/<id>.txt</code></td><td>plain text transcript</td></tr> + <tr><td><code>{{PUBLIC_URL}}/share/<id>.json</code></td><td>the raw data, as <code>claude-logbook --json -s</code> prints it</td></tr> + </table> + + <h2>Before you share</h2> + <div class="note"> + <p>A share holds the <strong>whole conversation</strong>: your prompts, Claude's answers, + the tool calls and the project path. Anyone with the link can read it. It is not + encrypted, and this server can read it too.</p> + </div> + <ul> + <li><code>--share</code> warns if it spots things that look like API keys, tokens or private keys.</li> + <li>Shares expire after 30 days unless you pick <code>--expire 1d</code>, <code>7d</code> or <code>90d</code>.</li> + <li>Only the machine that created a share holds its secret and can update or delete it + (<code>~/.local/state/claude-logbook/shares.json</code>).</li> + <li>Share pages are marked <code>noindex</code>, but a link is only as private as the places you paste it.</li> + </ul> + + <h2>API</h2> + <p>The CLI talks to a small JSON API; you can use it directly:</p> +<pre><code>POST /api/shares {"payload": {...}, "expire": "30d"} → {id, url, secret, expires} +PUT /api/shares/<id> Authorization: Bearer <secret> replace the content +DELETE /api/shares/<id> Authorization: Bearer <secret> delete it</code></pre> + <p>The payload is the JSON of <code>claude-logbook --json -s REF</code>, one session. + The server builds the page itself and does not accept HTML.</p> + + <footer> + claude-logbook · <a href="https://github.com/ElvisClaros/claude-logbook">source on GitHub</a> · + <a href="https://pypi.org/project/claude-logbook/">PyPI</a> + </footer> +</main> +</body> +</html> diff --git a/server/limit.go b/server/limit.go new file mode 100644 index 0000000..1b93dd7 --- /dev/null +++ b/server/limit.go @@ -0,0 +1,127 @@ +package main + +import ( + "net" + "net/http" + "strings" + "sync" + "time" +) + +// Limiter is a token bucket per key (the client IP): `burst` requests at +// once, refilled at `burst` per `per`. In memory: a restart forgets it. +type Limiter struct { + burst float64 + rate float64 // tokens per second + mu sync.Mutex + buckets map[string]*bucket + now func() time.Time +} + +type bucket struct { + tokens float64 + last time.Time +} + +func NewLimiter(burst int, per time.Duration) *Limiter { + return &Limiter{burst: float64(burst), rate: float64(burst) / per.Seconds(), + buckets: map[string]*bucket{}, now: time.Now} +} + +func (l *Limiter) Allow(key string) bool { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + b, ok := l.buckets[key] + if !ok { + b = &bucket{tokens: l.burst, last: now} + l.buckets[key] = b + } + b.tokens += now.Sub(b.last).Seconds() * l.rate + if b.tokens > l.burst { + b.tokens = l.burst + } + b.last = now + if b.tokens < 1 { + return false + } + b.tokens-- + return true +} + +// Prune drops the buckets that are full again: they behave as new ones. +func (l *Limiter) Prune() { + l.mu.Lock() + defer l.mu.Unlock() + now := l.now() + for k, b := range l.buckets { + if b.tokens+now.Sub(b.last).Seconds()*l.rate >= l.burst { + delete(l.buckets, k) + } + } +} + +// ClientIP trusts X-Forwarded-For only when the connection comes from the +// proxy (Nginx Proxy Manager); anyone else could write that header. +type ClientIP struct { + trusted []*net.IPNet +} + +func NewClientIP(spec string) (*ClientIP, error) { + c := &ClientIP{} + for _, part := range strings.Split(spec, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + if !strings.Contains(part, "/") { + if strings.Contains(part, ":") { + part += "/128" + } else { + part += "/32" + } + } + _, n, err := net.ParseCIDR(part) + if err != nil { + return nil, err + } + c.trusted = append(c.trusted, n) + } + return c, nil +} + +func (c *ClientIP) isTrusted(ip net.IP) bool { + for _, n := range c.trusted { + if n.Contains(ip) { + return true + } + } + return false +} + +func (c *ClientIP) Of(r *http.Request) string { + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + host = r.RemoteAddr + } + peer := net.ParseIP(host) + if peer == nil || !c.isTrusted(peer) { + return host + } + // Rightmost address that is not a trusted proxy: what the client put + // further left could be invented. + hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",") + for i := len(hops) - 1; i >= 0; i-- { + ip := net.ParseIP(strings.TrimSpace(hops[i])) + if ip == nil { + break + } + if !c.isTrusted(ip) { + return ip.String() + } + } + if real := net.ParseIP(strings.TrimSpace(r.Header.Get("X-Real-IP"))); real != nil { + return real.String() + } + return host +} diff --git a/server/main.go b/server/main.go new file mode 100644 index 0000000..617a9b1 --- /dev/null +++ b/server/main.go @@ -0,0 +1,431 @@ +// Command server publishes claude-logbook sessions at /share/<id>. +// +// Anyone may create a share (that is what `claude-logbook --share` does); +// only whoever holds the secret returned on creation may replace or delete +// it. Abuse is held back by size limits, payload validation and a rate limit +// per client IP. +package main + +import ( + _ "embed" + "encoding/json" + "errors" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + "strings" + "time" +) + +//go:generate cp ../claude_logbook/template.html template.html + +//go:embed template.html +var templateHTML string + +//go:embed home.html +var homeHTML string + +// TTLs the client may ask for; the first is the default. +var ttls = map[string]time.Duration{ + "1d": 24 * time.Hour, "7d": 7 * 24 * time.Hour, + "30d": 30 * 24 * time.Hour, "90d": 90 * 24 * time.Hour, +} + +const defaultTTL = "30d" + +type Config struct { + Addr string + DataDir string + PublicURL string + MaxBytes int64 + MaxSessions int + TrustedProxy string + CreatesPerH int + WritesPerH int +} + +func env(key, def string) string { + if v := os.Getenv(key); v != "" { + return v + } + return def +} + +func envInt(key string, def int64) int64 { + if v := os.Getenv(key); v != "" { + if n, err := strconv.ParseInt(v, 10, 64); err == nil { + return n + } + log.Fatalf("%s: not a number: %q", key, v) + } + return def +} + +type Server struct { + cfg Config + store *Store + page *Page + ip *ClientIP + creates *Limiter + writes *Limiter + home []byte +} + +func NewServer(cfg Config) (*Server, error) { + store, err := NewStore(cfg.DataDir) + if err != nil { + return nil, err + } + page, err := NewPage(templateHTML) + if err != nil { + return nil, err + } + ip, err := NewClientIP(cfg.TrustedProxy) + if err != nil { + return nil, fmt.Errorf("TRUSTED_PROXY: %v", err) + } + home := strings.ReplaceAll(homeHTML, "{{PUBLIC_URL}}", cfg.PublicURL) + return &Server{cfg: cfg, store: store, page: page, ip: ip, + creates: NewLimiter(cfg.CreatesPerH, time.Hour), + writes: NewLimiter(cfg.WritesPerH, time.Hour), + home: []byte(home)}, nil +} + +func (s *Server) Routes() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /{$}", s.handleHome) + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.Write([]byte("ok\n")) + }) + mux.HandleFunc("GET /share/{name}", s.handleShare) + mux.HandleFunc("POST /api/shares", s.handleCreate) + mux.HandleFunc("PUT /api/shares/{id}", s.handleUpdate) + mux.HandleFunc("DELETE /api/shares/{id}", s.handleDelete) + return logRequests(securityHeaders(mux)) +} + +// ──────────────────────────────── pages ────────────────────────────────── + +func (s *Server) handleHome(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; img-src data:; "+ + "base-uri 'none'; form-action 'none'; frame-ancestors 'none'") + w.Header().Set("Cache-Control", "public, max-age=300") + w.Write(s.home) +} + +func (s *Server) handleShare(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + id, ext, _ := strings.Cut(name, ".") + raw, _, err := s.store.Get(id) + if errors.Is(err, ErrNotFound) { + http.Error(w, "share not found (it may have expired or been deleted)", http.StatusNotFound) + return + } + if err != nil { + s.fail(w, err) + return + } + h := w.Header() + h.Set("Cache-Control", "private, no-cache") + h.Set("X-Robots-Tag", "noindex, nofollow") + switch ext { + case "": + h.Set("Content-Type", "text/html; charset=utf-8") + h.Set("Content-Security-Policy", s.page.csp) + w.Write(s.page.Render(raw)) + case "json": + h.Set("Content-Type", "application/json; charset=utf-8") + w.Write(raw) + case "txt": + p, _, err := ParsePayload(raw, 1<<30) + if err != nil { + s.fail(w, err) + return + } + h.Set("Content-Type", "text/plain; charset=utf-8") + w.Write(RenderText(p)) + default: + http.NotFound(w, r) + } +} + +// ──────────────────────────────── api ──────────────────────────────────── + +type writeReq struct { + Payload json.RawMessage `json:"payload"` + Expire string `json:"expire"` +} + +type shareResp struct { + ID string `json:"id"` + URL string `json:"url"` + Secret string `json:"secret,omitempty"` + Expires time.Time `json:"expires"` +} + +func jsonError(w http.ResponseWriter, code int, msg string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(code) + json.NewEncoder(w).Encode(map[string]string{"error": msg}) +} + +func (s *Server) fail(w http.ResponseWriter, err error) { + log.Printf("error: %v", err) + jsonError(w, http.StatusInternalServerError, "internal error") +} + +// readWrite decodes and validates a POST/PUT body. ok=false means the error +// response was already written. +func (s *Server) readWrite(w http.ResponseWriter, r *http.Request, needPayload bool) (clean []byte, ttl time.Duration, ok bool) { + r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxBytes) + var req writeReq + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + if err := dec.Decode(&req); err != nil { + var tooBig *http.MaxBytesError + if errors.As(err, &tooBig) { + jsonError(w, http.StatusRequestEntityTooLarge, + fmt.Sprintf("payload larger than %d bytes", s.cfg.MaxBytes)) + return nil, 0, false + } + jsonError(w, http.StatusBadRequest, "body: "+err.Error()) + return nil, 0, false + } + if req.Expire != "" { + var known bool + if ttl, known = ttls[req.Expire]; !known { + jsonError(w, http.StatusBadRequest, "expire: one of 1d, 7d, 30d, 90d") + return nil, 0, false + } + } + if len(req.Payload) == 0 { + if needPayload { + jsonError(w, http.StatusBadRequest, "payload: missing") + return nil, 0, false + } + return nil, ttl, true + } + _, clean, err := ParsePayload(req.Payload, s.cfg.MaxSessions) + if err != nil { + jsonError(w, http.StatusBadRequest, err.Error()) + return nil, 0, false + } + return clean, ttl, true +} + +func bearer(r *http.Request) string { + h := r.Header.Get("Authorization") + if t, ok := strings.CutPrefix(h, "Bearer "); ok { + return strings.TrimSpace(t) + } + return "" +} + +func (s *Server) url(id string) string { return s.cfg.PublicURL + "/share/" + id } + +func (s *Server) handleCreate(w http.ResponseWriter, r *http.Request) { + ip := s.ip.Of(r) + if !s.creates.Allow(ip) { + w.Header().Set("Retry-After", "600") + jsonError(w, http.StatusTooManyRequests, "too many shares from this address; try later") + return + } + clean, ttl, ok := s.readWrite(w, r, true) + if !ok { + return + } + if ttl == 0 { + ttl = ttls[defaultTTL] + } + id, secret, meta, err := s.store.Create(clean, ttl, ip) + if err != nil { + s.fail(w, err) + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("Location", "/share/"+id) + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(shareResp{ID: id, URL: s.url(id), Secret: secret, Expires: meta.Expires}) +} + +func (s *Server) authError(w http.ResponseWriter, err error) { + switch { + case errors.Is(err, ErrNotFound): + jsonError(w, http.StatusNotFound, "share not found") + case errors.Is(err, ErrDenied): + jsonError(w, http.StatusForbidden, "wrong secret") + default: + s.fail(w, err) + } +} + +func (s *Server) writeAllowed(w http.ResponseWriter, r *http.Request) (string, bool) { + if !s.writes.Allow(s.ip.Of(r)) { + w.Header().Set("Retry-After", "60") + jsonError(w, http.StatusTooManyRequests, "too many requests; try later") + return "", false + } + secret := bearer(r) + if secret == "" { + jsonError(w, http.StatusUnauthorized, "missing Authorization: Bearer <secret>") + return "", false + } + return secret, true +} + +func (s *Server) handleUpdate(w http.ResponseWriter, r *http.Request) { + secret, ok := s.writeAllowed(w, r) + if !ok { + return + } + clean, ttl, ok := s.readWrite(w, r, true) + if !ok { + return + } + id := r.PathValue("id") + meta, err := s.store.Update(id, secret, clean, ttl) + if err != nil { + s.authError(w, err) + return + } + w.Header().Set("Content-Type", "application/json; charset=utf-8") + json.NewEncoder(w).Encode(shareResp{ID: id, URL: s.url(id), Expires: meta.Expires}) +} + +func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) { + secret, ok := s.writeAllowed(w, r) + if !ok { + return + } + if err := s.store.Delete(r.PathValue("id"), secret); err != nil { + s.authError(w, err) + return + } + w.WriteHeader(http.StatusNoContent) +} + +// ──────────────────────────────── middleware ───────────────────────────── + +func securityHeaders(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("X-Frame-Options", "DENY") + h.Set("Cross-Origin-Opener-Policy", "same-origin") + next.ServeHTTP(w, r) + }) +} + +type statusWriter struct { + http.ResponseWriter + status int + bytes int +} + +func (sw *statusWriter) WriteHeader(code int) { + sw.status = code + sw.ResponseWriter.WriteHeader(code) +} + +func (sw *statusWriter) Write(b []byte) (int, error) { + if sw.status == 0 { + sw.status = http.StatusOK + } + n, err := sw.ResponseWriter.Write(b) + sw.bytes += n + return n, err +} + +// logRequests logs method, path, status and size; never bodies or headers, +// which carry transcripts and secrets. +func logRequests(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + sw := &statusWriter{ResponseWriter: w} + next.ServeHTTP(sw, r) + if r.URL.Path == "/healthz" { + return + } + log.Printf("%s %s %d %dB %s", r.Method, r.URL.Path, sw.status, sw.bytes, + time.Since(start).Round(time.Millisecond)) + }) +} + +// ──────────────────────────────── main ─────────────────────────────────── + +func (s *Server) janitor(every time.Duration) { + for range time.Tick(every) { + if n := s.store.Sweep(); n > 0 { + log.Printf("swept %d expired shares", n) + } + s.creates.Prune() + s.writes.Prune() + } +} + +func healthcheck(addr string) int { + if strings.HasPrefix(addr, ":") { + addr = "127.0.0.1" + addr + } + c := http.Client{Timeout: 3 * time.Second} + resp, err := c.Get("http://" + addr + "/healthz") + if err != nil { + fmt.Fprintln(os.Stderr, err) + return 1 + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return 1 + } + return 0 +} + +func main() { + cfg := Config{} + flag.StringVar(&cfg.Addr, "addr", env("ADDR", ":8181"), "listen address") + flag.StringVar(&cfg.DataDir, "data", env("DATA_DIR", "/data"), "where shares are stored") + flag.StringVar(&cfg.PublicURL, "public-url", env("PUBLIC_URL", "https://claude-logbook.all.ar"), "base of the URLs handed out") + flag.Int64Var(&cfg.MaxBytes, "max-bytes", envInt("MAX_BYTES", 10<<20), "largest request body") + maxSessions := flag.Int64("max-sessions", envInt("MAX_SESSIONS", 1), "sessions per share") + flag.StringVar(&cfg.TrustedProxy, "trusted-proxy", env("TRUSTED_PROXY", ""), "IPs/CIDRs whose X-Forwarded-For is believed (comma separated)") + creates := flag.Int64("creates-per-hour", envInt("CREATES_PER_HOUR", 10), "new shares per IP and hour") + writes := flag.Int64("writes-per-hour", envInt("WRITES_PER_HOUR", 60), "updates and deletes per IP and hour") + check := flag.Bool("healthcheck", false, "query /healthz and exit (for Docker HEALTHCHECK)") + flag.Parse() + cfg.MaxSessions, cfg.CreatesPerH, cfg.WritesPerH = int(*maxSessions), int(*creates), int(*writes) + cfg.PublicURL = strings.TrimRight(cfg.PublicURL, "/") + + if *check { + os.Exit(healthcheck(cfg.Addr)) + } + + srv, err := NewServer(cfg) + if err != nil { + log.Fatal(err) + } + if cfg.TrustedProxy == "" { + log.Printf("TRUSTED_PROXY is empty: X-Forwarded-For is ignored and the " + + "rate limit counts the proxy's address, not the client's") + } + srv.store.Sweep() + go srv.janitor(time.Hour) + + hs := &http.Server{ + Addr: cfg.Addr, + Handler: srv.Routes(), + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + IdleTimeout: 120 * time.Second, + MaxHeaderBytes: 16 << 10, + } + log.Printf("listening on %s, data in %s, public URL %s", cfg.Addr, cfg.DataDir, cfg.PublicURL) + log.Fatal(hs.ListenAndServe()) +} diff --git a/server/render.go b/server/render.go new file mode 100644 index 0000000..c23df78 --- /dev/null +++ b/server/render.go @@ -0,0 +1,206 @@ +package main + +// The server never accepts HTML: it takes the same JSON `claude-logbook +// --json -s` prints, checks its shape and builds the page itself from the +// CLI's own template. The only scripts that run under this domain are the +// template's, and the CSP pins them by hash. + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" + "time" +) + +const dataMarker = "__DATA__" + +// ──────────────────────────────── validation ───────────────────────────── + +type Block struct { + R string `json:"r"` + X string `json:"x"` +} + +// Session mirrors a record of sessions.py without its internal keys. +// Pointers are the keys that may be null. +type Session struct { + ID string `json:"id"` + P string `json:"p"` + B *string `json:"b"` + T *string `json:"t"` + AI bool `json:"ai"` + N bool `json:"n"` + E bool `json:"e"` + I bool `json:"i"` + F *string `json:"f"` + L *string `json:"l"` + D *float64 `json:"d"` + U int `json:"u"` + A int `json:"a"` + K float64 `json:"k"` + V *string `json:"v"` + C []Block `json:"c"` +} + +type Payload struct { + S []Session `json:"s"` + M []json.RawMessage `json:"m"` +} + +var sessionIDRE = regexp.MustCompile(`^[0-9a-zA-Z-]{1,64}$`) + +// ParsePayload checks that raw has exactly the shape the template reads and +// returns it re-encoded, so nothing the server does not know travels on. +func ParsePayload(raw []byte, maxSessions int) (*Payload, []byte, error) { + // Keys the server does not know are dropped rather than refused: a newer + // CLI may add one, and re-encoding below leaves only what is listed here. + dec := json.NewDecoder(bytes.NewReader(raw)) + var p Payload + if err := dec.Decode(&p); err != nil { + return nil, nil, fmt.Errorf("payload: %v", err) + } + if dec.More() { + return nil, nil, errors.New("payload: trailing data") + } + if len(p.S) == 0 || len(p.S) > maxSessions { + return nil, nil, fmt.Errorf("payload: between 1 and %d sessions", maxSessions) + } + if len(p.M) != 0 { + return nil, nil, errors.New("payload: memories are not shared") + } + for i, s := range p.S { + if !sessionIDRE.MatchString(s.ID) { + return nil, nil, fmt.Errorf("payload: session %d: bad id", i) + } + if s.C == nil { + return nil, nil, fmt.Errorf("payload: session %d: no c", i) + } + for j, b := range s.C { + if b.R != "u" && b.R != "a" && b.R != "t" { + return nil, nil, fmt.Errorf("payload: session %d block %d: bad r", i, j) + } + } + } + p.M = []json.RawMessage{} + clean, err := json.Marshal(p) + return &p, clean, err +} + +// ──────────────────────────────── html ─────────────────────────────────── + +type Page struct { + before, after string + csp string +} + +var scriptRE = regexp.MustCompile(`(?s)<script([^>]*)>(.*?)</script>`) + +// 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 <script> at the first "</", so it is written as "<\/", a JSON escape +// that JSON.parse turns back into "</". Go already escapes <, > and & as +// <..., which covers "<!--" too. +func EncodeData(clean []byte) []byte { + return bytes.ReplaceAll(clean, []byte("</"), []byte(`<\/`)) +} + +func (pg *Page) Render(clean []byte) []byte { + var b bytes.Buffer + b.WriteString(pg.before) + b.Write(EncodeData(clean)) + b.WriteString(pg.after) + return b.Bytes() +} + +// ──────────────────────────────── text ─────────────────────────────────── + +func deref(s *string, alt string) string { + if s == nil || *s == "" { + return alt + } + return *s +} + +func fmtStamp(s *string) string { + if s == nil { + return "?" + } + t, err := time.Parse(time.RFC3339, *s) + if err != nil { + return *s + } + return t.UTC().Format("2006-01-02 15:04 UTC") +} + +// RenderText is the transcript in p |