aboutsummaryrefslogtreecommitdiffstats
path: root/server/render.go
blob: 6acb8aa459e327e0c583fd2f076740cce57ca1ad (plain)
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
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"`
	Src string `json:"src,omitempty"`
}

// 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"`
	H  int      `json:"h"`
	O  *string  `json:"o"`
	OT *string  `json:"ot"`
}

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 {
			switch b.R {
			case "u", "a", "t", "c", "d":
				if b.Src != "" {
					return nil, nil, fmt.Errorf("payload: session %d block %d: src on a %q block", i, j, b.R)
				}
			case "i", "v":
				if b.Src != "" && !validImage(b.Src) {
					return nil, nil, fmt.Errorf("payload: session %d block %d: not a png, jpeg, gif or webp image", i, j)
				}
			default:
				return nil, nil, fmt.Errorf("payload: session %d block %d: bad r", i, j)
			}
		}
		if s.H < 0 || s.H > len(s.C) {
			return nil, nil, fmt.Errorf("payload: session %d: bad h", i)
		}
		if s.O != nil && !sessionIDRE.MatchString(*s.O) {
			return nil, nil, fmt.Errorf("payload: session %d: bad o", i)
		}
	}
	p.M = []json.RawMessage{}
	clean, err := json.Marshal(p)
	return &p, clean, err
}

// imageMagic is how each accepted format starts. SVG is not among them: it
// is a document that can carry a script.
var imageMagic = map[string][]string{
	"png":  {"\x89PNG\r\n\x1a\n"},
	"jpeg": {"\xff\xd8\xff"},
	"gif":  {"GIF87a", "GIF89a"},
	"webp": {"RIFF"},
}

// validImage accepts only a base64 data: URL whose bytes really are the
// raster format it claims.
func validImage(src string) bool {
	rest, ok := strings.CutPrefix(src, "data:image/")
	if !ok {
		return false
	}
	kind, data, ok := strings.Cut(rest, ";base64,")
	if !ok {
		return false
	}
	magics, ok := imageMagic[kind]
	if !ok {
		return false
	}
	raw, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return false
	}
	if kind == "webp" && (len(raw) < 12 || string(raw[8:12]) != "WEBP") {
		return false
	}
	for _, m := range magics {
		if bytes.HasPrefix(raw, []byte(m)) {
			return true
		}
	}
	return false
}

// ──────────────────────────────── 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")
}

// lineBlock are the blocks printed as one "> " line; a run of them goes
// together, after a blank line.
var lineBlock = map[string]bool{"t": true, "d": true, "i": true, "v": true}

// RenderText is the transcript in plain text, in the order the terminal
// shows it with `claude-logbook -s`.
func RenderText(p *Payload) []byte {
	var b strings.Builder
	for i, s := range p.S {
		if i > 0 {
			b.WriteString("\n\n")
		}
		title := deref(s.T, "Untitled session")
		fmt.Fprintf(&b, "# %s\n\n", title)
		fmt.Fprintf(&b, "project:  %s\n", s.P)
		if s.B != nil && *s.B != "" {
			fmt.Fprintf(&b, "branch:   %s\n", *s.B)
		}
		fmt.Fprintf(&b, "from:     %s\nto:       %s\n", fmtStamp(s.F), fmtStamp(s.L))
		fmt.Fprintf(&b, "messages: %d yours / %d from Claude\n", s.U, s.A)
		if s.V != nil && *s.V != "" {
			fmt.Fprintf(&b, "version:  Claude Code %s\n", *s.V)
		}
		fmt.Fprintf(&b, "session:  %s\n",