1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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 ""
|