-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathapi.test.ts
More file actions
2540 lines (2283 loc) · 95.3 KB
/
Copy pathapi.test.ts
File metadata and controls
2540 lines (2283 loc) · 95.3 KB
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { createApp } from "../server/app.ts";
import { JsonFileStore } from "../server/storage.ts";
function makeApp(
authToken?: string,
opts?: {
publicRead?: "session" | "full";
basePath?: string;
viewerHtml?: string;
screenshots?: boolean;
maxHoldConnections?: number;
},
) {
const dir = mkdtempSync(join(tmpdir(), "sideshow-test-"));
const store = new JsonFileStore(join(dir, "data.json"));
const { viewerHtml = "<html><head></head><body>viewer</body></html>", ...rest } = opts ?? {};
return createApp({
store,
viewerHtml,
guideMarkdown: "# guide",
setupText: "# setup",
agentHowtoText: "# agent how-to",
authToken,
...rest,
});
}
const json = (body: unknown) => ({
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
const authedJson = (body: unknown, token = "secret") => ({
...json(body),
headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
});
test("publish without session auto-creates one", async () => {
const app = makeApp();
const res = await app.request(
"/api/snippets",
json({ html: "<p>hi</p>", agent: "pi", title: "First" }),
);
assert.equal(res.status, 201);
const snippet = (await res.json()) as any;
assert.ok(snippet.id);
assert.ok(snippet.sessionId);
assert.equal(snippet.title, "First");
assert.equal(snippet.version, 1);
const sessions = (await (await app.request("/api/sessions")).json()) as any;
assert.equal(sessions.length, 1);
assert.equal(sessions[0].agent, "pi");
assert.equal(sessions[0].surfaceCount, 1);
});
test("publish into an existing session groups snippets", async () => {
const app = makeApp();
const first = (await (
await app.request("/api/snippets", json({ html: "<p>1</p>", agent: "amp" }))
).json()) as any;
await app.request("/api/snippets", json({ html: "<p>2</p>", session: first.sessionId }));
const list = (await (
await app.request(`/api/sessions/${first.sessionId}/snippets`)
).json()) as any;
assert.equal(list.length, 2);
});
test("publish with sessionTitle names the auto-created session", async () => {
const app = makeApp();
const res = await app.request(
"/api/snippets",
json({ html: "<p>x</p>", agent: "pi", sessionTitle: "Auth refactor" }),
);
assert.equal(res.status, 201);
const snippet = (await res.json()) as any;
const sessions = (await (await app.request("/api/sessions")).json()) as any;
assert.equal(sessions.length, 1);
assert.equal(sessions[0].id, snippet.sessionId);
assert.equal(sessions[0].title, "Auth refactor");
});
test("sessionTitle never retitles an existing session", async () => {
const app = makeApp();
const first = (await (
await app.request("/api/snippets", json({ html: "<p>1</p>", sessionTitle: "Original" }))
).json()) as any;
// the user renames the session in the viewer...
await app.request(`/api/sessions/${first.sessionId}`, {
...json({ title: "User's pick" }),
method: "PATCH",
});
// ...and a later publish carrying a sessionTitle must not clobber it
const res = await app.request(
"/api/snippets",
json({ html: "<p>2</p>", session: first.sessionId, sessionTitle: "Clobber attempt" }),
);
assert.equal(res.status, 201);
const sessions = (await (await app.request("/api/sessions")).json()) as any;
assert.equal(sessions.length, 1);
assert.equal(sessions[0].title, "User's pick");
});
test("publish into unknown session 404s instead of silently creating", async () => {
const app = makeApp();
const res = await app.request("/api/snippets", json({ html: "<p>x</p>", session: "nope" }));
assert.equal(res.status, 404);
});
test("publishes a combined html+diff surface; /s server-renders both parts opaque-sandboxed", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({
title: "Review",
parts: [
{ kind: "html", html: "<p>diagram</p>" },
{ kind: "diff", patch: "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b", layout: "split" },
],
}),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
// the write response is lean — kinds, no part bodies echoed back
assert.deepEqual(surface.kinds, ["html", "diff"]);
assert.equal(surface.parts, undefined);
// the full record keeps the html and the diff patch
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces.length, 2);
assert.equal(full.surfaces[0].html, "<p>diagram</p>");
assert.equal(full.surfaces[1].patch, "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b");
// /s renders the html part...
const part0 = await app.request(`/s/${surface.id}?part=0`);
assert.ok((await part0.text()).includes("<p>diagram</p>"));
// ...and now also server-renders the diff part (no viewer round-trip): the
// @pierre/diffs SSR output wraps each file in a <diffs-container>.
const part1 = await app.request(`/s/${surface.id}?part=1`);
assert.equal(part1.status, 200);
assert.ok((await part1.text()).includes("diffs-container"));
// Both carry the `sandbox` CSP response header, so a top-level load of the
// document (not just the embedded iframe) runs in an opaque origin — never the
// board origin. allow-scripts keeps the bridge working; allow-same-origin must
// never appear (it would defeat the sandbox).
for (const res of [part0, part1]) {
const csp = res.headers.get("content-security-policy") ?? "";
assert.match(csp, /\bsandbox\b/);
assert.match(csp, /\ballow-scripts\b/);
assert.doesNotMatch(csp, /allow-same-origin/);
}
});
test("the viewer render round-trip (POST /api/frames + GET /f/:id) is gone", async () => {
// Rich parts now render server-side at /s/:id, so the transient frame store and
// its write endpoint were removed; both must be unreachable (no public-read
// POST exception lingering, no in-memory doc host).
const app = makeApp();
assert.equal((await app.request("/api/frames", json({ html: "<p>x</p>" }))).status, 404);
assert.equal((await app.request("/f/anything")).status, 404);
});
test("GET /s/:id serves the viewer shell with link-preview metadata", async () => {
const app = makeApp();
const res = await app.request(
"/api/snippets",
json({ title: "Auth Flow", html: "<p>diagram</p>", sessionTitle: "Secret session" }),
);
const surface = (await res.json()) as any;
const page = await app.request(`https://board.test/s/${surface.id}`);
assert.equal(page.status, 200);
assert.ok(page.headers.get("content-type")?.includes("text/html"));
assert.equal(page.headers.get("content-security-policy"), null);
const body = await page.text();
assert.ok(body.includes("viewer"), "should serve the trusted viewer shell");
assert.doesNotMatch(body, /<p>diagram<\/p>/, "should not inline agent HTML");
assert.match(body, /<meta property="og:title" content="Auth Flow">/);
assert.match(body, /<meta name="twitter:title" content="Auth Flow">/);
assert.match(body, /<meta property="og:description" content="A https:\/\/sideshow\.sh surface">/);
assert.match(
body,
/<meta name="twitter:description" content="A https:\/\/sideshow\.sh surface">/,
);
assert.doesNotMatch(body, /Secret session/);
});
test("GET /s/:id emits absolute token-free canonical and preview image URLs", async () => {
const app = makeApp("secret");
const res = await app.request(
"https://board.test/api/snippets",
authedJson({ title: "Preview", html: "<p>x</p>" }),
);
const surface = (await res.json()) as any;
const body = await (await app.request(`https://board.test/s/${surface.id}?key=secret`)).text();
const canonical = `https://board.test/s/${surface.id}`;
const image = `https://board.test/s/${surface.id}.png?card=1`;
assert.match(body, new RegExp(`<link rel="canonical" href="${canonical}">`));
assert.match(body, new RegExp(`<meta property="og:url" content="${canonical}">`));
assert.match(
body,
new RegExp(`<meta property="og:image" content="${image.replace("?", "\\?")}">`),
);
assert.match(
body,
new RegExp(`<meta name="twitter:image" content="${image.replace("?", "\\?")}">`),
);
for (const line of body.split("\n").filter((l) => /canonical|og:|twitter:/.test(l))) {
assert.doesNotMatch(line, /key=secret|secret/);
}
});
test("GET /s/:id?part=0 still serves an opaque sandboxed part document", async () => {
const app = makeApp();
const res = await app.request(
"/api/snippets",
json({ title: "Part", html: "<script>window.x=1</script><p>part</p>" }),
);
const surface = (await res.json()) as any;
const part = await app.request(`/s/${surface.id}?part=0`);
assert.equal(part.status, 200);
const csp = part.headers.get("content-security-policy") ?? "";
assert.match(csp, /\bsandbox\b/);
assert.match(csp, /\ballow-scripts\b/);
assert.doesNotMatch(csp, /allow-same-origin/);
assert.match(await part.text(), /<p>part<\/p>/);
});
test("GET /s/:id escapes surface metadata in preview tags", async () => {
const app = makeApp();
const title = `A "quoted" <tag> & more`;
const res = await app.request("/api/snippets", json({ title, html: "<p>x</p>" }));
const surface = (await res.json()) as any;
const body = await (await app.request(`/s/${surface.id}`)).text();
assert.match(
body,
/<meta property="og:title" content="A "quoted" <tag> & more">/,
);
assert.doesNotMatch(body, /content="A "quoted" <tag> & more"/);
});
test("GET /s/:id preview metadata respects configured base path", async () => {
const app = makeApp(undefined, { basePath: "/u/alice" });
const res = await app.request("/api/snippets", json({ title: "Base", html: "<p>x</p>" }));
const surface = (await res.json()) as any;
const body = await (await app.request(`https://board.test/s/${surface.id}`)).text();
assert.match(
body,
new RegExp(`<link rel="canonical" href="https://board.test/u/alice/s/${surface.id}">`),
);
assert.match(
body,
new RegExp(
`<meta property="og:image" content="https://board.test/u/alice/s/${surface.id}\\.png\\?card=1">`,
),
);
assert.match(body, /window\.__SIDESHOW_BASE_PATH__="\/u\/alice"/);
});
test("/s served versioned + themed is cacheable; an unpinned load is not", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({ title: "C", parts: [{ kind: "code", code: "x", language: "text" }] }),
);
const { id, version } = (await res.json()) as any;
// What the viewer always sends (ver + theme pinned) is immutable → long-cache.
const pinned = await app.request(`/s/${id}?part=0&ver=${version}&theme=github&mode=light`);
assert.match(pinned.headers.get("cache-control") ?? "", /immutable/);
// A bare load resolves to "current", which can change → must not be cached.
const bare = await app.request(`/s/${id}?part=0`);
assert.match(bare.headers.get("cache-control") ?? "", /no-cache/);
});
test("a snippet's kits ride the html part and inject the kit CSS/JS at /s", async () => {
const app = makeApp();
const res = await app.request(
"/api/snippets",
json({ title: "Deck", html: "<div class=deck></div>", kits: ["slides"] }),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
// the kits persist on the stored html part
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.deepEqual(full.surfaces[0].kits, ["slides"]);
// /s injects the kit's css (rail/deck rules) and its behavior js
const doc = await (await app.request(`/s/${surface.id}?part=0`)).text();
assert.match(doc, /\.deck>\.slide/);
assert.match(doc, /querySelector\('\.deck'\)/);
// a plain snippet (no kits) gets neither
const plain = await app.request("/api/snippets", json({ title: "Plain", html: "<p>x</p>" }));
const plainSurface = (await plain.json()) as any;
const plainDoc = await (await app.request(`/s/${plainSurface.id}?part=0`)).text();
assert.doesNotMatch(plainDoc, /querySelector\('\.deck'\)/);
});
test("an unknown kit id is rejected before storage (400)", async () => {
const app = makeApp();
const bad = await app.request(
"/api/snippets",
json({ title: "x", html: "<p>x</p>", kits: ["bogus"] }),
);
assert.equal(bad.status, 400);
assert.match(((await bad.json()) as any).error, /unknown kit "bogus"/);
const badPart = await app.request(
"/api/surfaces",
json({ title: "x", parts: [{ kind: "html", html: "<p>x</p>", kits: ["bogus"] }] }),
);
assert.equal(badPart.status, 400);
});
test("GET /api/kits advertises the available kits without the css payload", async () => {
const app = makeApp();
const kits = (await (await app.request("/api/kits")).json()) as any[];
const ids = kits.map((k) => k.id);
assert.ok(ids.includes("issues") && ids.includes("slides"));
for (const k of kits) {
assert.ok(typeof k.summary === "string" && k.summary.length > 0);
assert.equal("css" in k, false);
}
});
test("REST surface routes reject malformed parts before storage", async () => {
const app = makeApp();
const badCreate = await app.request("/api/surfaces", json({ parts: [{ kind: "image" }] }));
assert.equal(badCreate.status, 400);
assert.match(((await badCreate.json()) as any).error, /assetId/);
assert.deepEqual(await (await app.request("/api/sessions")).json(), []);
const good = (await (
await app.request("/api/surfaces", json({ parts: [{ kind: "html", html: "<p>x</p>" }] }))
).json()) as any;
const badUpdate = await app.request(`/api/surfaces/${good.id}`, {
...json({ parts: [{ kind: "diff", files: [{ filename: "x", before: "a" }] }] }),
method: "PUT",
});
assert.equal(badUpdate.status, 400);
assert.match(((await badUpdate.json()) as any).error, /before.*after/);
const unchanged = (await (await app.request(`/api/surfaces/${good.id}`)).json()) as any;
assert.equal(unchanged.version, 1);
assert.deepEqual(unchanged.surfaces, [{ kind: "html", html: "<p>x</p>" }]);
});
test("publish_surface MCP tool round-trips a diff part", async () => {
const app = makeApp();
const list = (await (await app.request("/mcp", mcpCall(1, "tools/list"))).json()) as any;
const names = list.result.tools.map((t: any) => t.name);
assert.ok(names.includes("publish_surface"));
assert.ok(names.includes("publish_snippet")); // alias still advertised
const published = (await (
await app.request(
"/mcp",
mcpCall(2, "tools/call", {
name: "publish_surface",
arguments: {
title: "Diff",
parts: [{ kind: "diff", patch: "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-x\n+y" }],
},
}),
)
).json()) as any;
const payload = JSON.parse(published.result.content[0].text);
assert.ok(payload.id && payload.sessionId);
const full = (await (await app.request(`/api/surfaces/${payload.id}`)).json()) as any;
assert.equal(full.surfaces[0].kind, "diff");
assert.equal(full.surfaces[0].patch, "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-x\n+y");
});
test("publishes a markdown part; /s server-renders it to sandboxed html", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({ title: "Plan", parts: [{ kind: "markdown", markdown: "## Plan\n\n- step one" }] }),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
assert.deepEqual(surface.kinds, ["markdown"]);
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].kind, "markdown");
assert.equal(full.surfaces[0].markdown, "## Plan\n\n- step one");
// markdown now renders server-side: the prose is in the document, and it is
// served opaque-sandboxed (the load-bearing CSP header).
const doc = await app.request(`/s/${surface.id}?part=0`);
assert.equal(doc.status, 200);
const body = await doc.text();
assert.ok(body.includes("<h2>Plan</h2>"));
assert.ok(body.includes("step one"));
assert.match(doc.headers.get("content-security-policy") ?? "", /\bsandbox\b/);
});
test("publish_surface MCP tool keeps markdown parts and drops empty ones", async () => {
const app = makeApp();
const published = (await (
await app.request(
"/mcp",
mcpCall(2, "tools/call", {
name: "publish_surface",
arguments: {
title: "Notes",
parts: [
{ kind: "markdown", markdown: " " },
{ kind: "markdown", markdown: "real prose" },
],
},
}),
)
).json()) as any;
const payload = JSON.parse(published.result.content[0].text);
const full = (await (await app.request(`/api/surfaces/${payload.id}`)).json()) as any;
assert.equal(full.surfaces.length, 1);
assert.equal(full.surfaces[0].kind, "markdown");
assert.equal(full.surfaces[0].markdown, "real prose");
});
test("publish_surface MCP tool round-trips a terminal part", async () => {
const app = makeApp();
const published = (await (
await app.request(
"/mcp",
mcpCall(2, "tools/call", {
name: "publish_surface",
arguments: {
title: "Terminal",
parts: [
{ kind: "terminal", text: "$ echo hi\n\x1b[32mhi\x1b[0m", cols: 80, title: "sh" },
],
},
}),
)
).json()) as any;
const payload = JSON.parse(published.result.content[0].text);
assert.ok(payload.id && payload.sessionId);
const full = (await (await app.request(`/api/surfaces/${payload.id}`)).json()) as any;
assert.equal(full.surfaces[0].kind, "terminal");
assert.equal(full.surfaces[0].text, "$ echo hi\n\x1b[32mhi\x1b[0m");
assert.equal(full.surfaces[0].cols, 80);
assert.equal(full.surfaces[0].title, "sh");
// terminal now renders server-side (ansi_up → styled window) at /s
const doc = await app.request(`/s/${payload.id}?part=0`);
assert.equal(doc.status, 200);
assert.ok((await doc.text()).includes("term-body"));
});
test("publishes a mermaid part; /s emits a self-rendering CDN doc", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({ title: "Flow", parts: [{ kind: "mermaid", mermaid: "graph TD; A-->B" }] }),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
assert.deepEqual(surface.kinds, ["mermaid"]);
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].kind, "mermaid");
assert.equal(full.surfaces[0].mermaid, "graph TD; A-->B");
// mermaid can't render without a DOM, so /s emits a sandboxed doc that loads
// mermaid from the CDN and renders the source in-frame. The doc carries the
// source and the CDN import, and is served opaque-sandboxed.
const doc = await app.request(`/s/${surface.id}?part=0`);
assert.equal(doc.status, 200);
const body = await doc.text();
assert.ok(body.includes("esm.sh/mermaid"));
assert.ok(body.includes("graph TD; A--\\u003eB") || body.includes("graph TD; A-->B"));
assert.match(doc.headers.get("content-security-policy") ?? "", /\bsandbox\b/);
});
test("publishes a json part; round-trips data and 404s on /s", async () => {
const app = makeApp();
const data = {
name: "sideshow",
version: "1.2.3",
deps: ["a", "b"],
nested: { x: true, y: null },
};
const res = await app.request(
"/api/surfaces",
json({ title: "Config", parts: [{ kind: "json", data }] }),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
assert.deepEqual(surface.kinds, ["json"]);
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].kind, "json");
assert.deepEqual(full.surfaces[0].data, data);
// json is viewer-rendered data, not a sandboxed html doc
assert.equal((await app.request(`/s/${surface.id}?part=0`)).status, 404);
});
test("json part with null data is valid (null is a JSON value)", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({ title: "Null", parts: [{ kind: "json", data: null }] }),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].data, null);
});
test("json part without data key is rejected", async () => {
const app = makeApp();
const res = await app.request("/api/surfaces", json({ title: "Bad", parts: [{ kind: "json" }] }));
assert.equal(res.status, 400);
});
test("json part openDepth round-trips", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({ title: "Tree", parts: [{ kind: "json", data: { a: { b: 1 } }, openDepth: 2 }] }),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].openDepth, 2);
});
test("publishes a code part; round-trips code/lang/title and 404s on /s", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({
title: "Entry",
parts: [{ kind: "code", code: "const x = 42;\n", language: "ts", title: "a.ts" }],
}),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
assert.deepEqual(surface.kinds, ["code"]);
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].kind, "code");
assert.equal(full.surfaces[0].code, "const x = 42;\n");
assert.equal(full.surfaces[0].language, "ts");
assert.equal(full.surfaces[0].title, "a.ts");
// code now renders server-side (shiki) at /s, with the filename and copy button
const doc = await app.request(`/s/${surface.id}?part=0`);
assert.equal(doc.status, 200);
const body = await doc.text();
assert.ok(body.includes("shiki"));
assert.ok(body.includes("a.ts"));
});
test("code part without code is rejected", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({ title: "Bad", parts: [{ kind: "code", language: "ts" }] }),
);
assert.equal(res.status, 400);
});
test("code part with lineStart round-trips", async () => {
const app = makeApp();
const res = await app.request(
"/api/surfaces",
json({
title: "Excerpt",
parts: [
{
kind: "code",
code: "const x = 1;\nconst y = 2;\n",
language: "ts",
title: "a.ts",
lineStart: 80,
},
],
}),
);
assert.equal(res.status, 201);
const surface = (await res.json()) as any;
const full = (await (await app.request(`/api/surfaces/${surface.id}`)).json()) as any;
assert.equal(full.surfaces[0].lineStart, 80);
});
test("publish_surface MCP tool keeps mermaid parts and drops empty ones", async () => {
const app = makeApp();
const published = (await (
await app.request(
"/mcp",
mcpCall(2, "tools/call", {
name: "publish_surface",
arguments: {
title: "Diagram",
parts: [
{ kind: "mermaid", mermaid: " " },
{ kind: "mermaid", mermaid: "graph TD; A-->B" },
],
},
}),
)
).json()) as any;
const payload = JSON.parse(published.result.content[0].text);
const full = (await (await app.request(`/api/surfaces/${payload.id}`)).json()) as any;
assert.equal(full.surfaces.length, 1);
assert.equal(full.surfaces[0].kind, "mermaid");
assert.equal(full.surfaces[0].mermaid, "graph TD; A-->B");
});
test("update bumps version and keeps history; old version renderable", async () => {
const app = makeApp();
const s = (await (
await app.request("/api/snippets", json({ html: "<p>v1</p>", title: "T" }))
).json()) as any;
const res = await app.request(`/api/snippets/${s.id}`, {
...json({ html: "<p>v2</p>" }),
method: "PUT",
});
const updated = (await res.json()) as any;
assert.equal(updated.version, 2);
const full = (await (await app.request(`/api/snippets/${s.id}`)).json()) as any;
assert.equal(full.history.length, 1);
assert.equal(full.history[0].surfaces[0].html, "<p>v1</p>");
const current = await (await app.request(`/s/${s.id}?part=0`)).text();
assert.ok(current.includes("<p>v2</p>"));
const old = await (await app.request(`/s/${s.id}?part=0&ver=1`)).text();
assert.ok(old.includes("<p>v1</p>"));
});
test("snippet page is wrapped with CSP, bridge, and kit", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
const page = await (await app.request(`/s/${s.id}?part=0`)).text();
assert.ok(page.includes("Content-Security-Policy"));
assert.ok(page.includes("window.sendPrompt"));
assert.ok(page.includes("__sideshow"));
// Snippet kit: SVG utilities in the stylesheet and the shared arrow marker
// injected before the snippet body so url(#arrow) resolves.
assert.ok(page.includes(".c-blue"));
assert.ok(page.indexOf('<marker id="arrow"') < page.indexOf("<p>x</p>"));
assert.ok(page.includes('<marker id="arrow"'));
});
test("comments attach to snippets and filter by author/after", async () => {
const app = makeApp();
const s = (await (
await app.request("/api/snippets", json({ html: "<p>x</p>", title: "Sketch" }))
).json()) as any;
await app.request("/api/comments", json({ snippet: s.id, text: "love it", author: "user" }));
await app.request("/api/comments", json({ snippet: s.id, text: "thanks", author: "claude" }));
const all = (await (await app.request(`/api/comments?session=${s.sessionId}`)).json()) as any;
assert.equal(all.comments.length, 2);
assert.equal(all.comments[0].postTitle, "Sketch");
// explicit after=0: re-read from the start regardless of the agent cursor
const users = (await (
await app.request(`/api/comments?session=${s.sessionId}&author=user&after=0`)
).json()) as any;
assert.equal(users.comments.length, 1);
assert.equal(users.comments[0].text, "love it");
const later = (await (
await app.request(`/api/comments?session=${s.sessionId}&after=${all.lastSeq}`)
).json()) as any;
assert.equal(later.comments.length, 0);
});
test("a comment must target a surface", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
// no surface/snippet id — there is no session-level thread to land in
const res = await app.request("/api/comments", json({ session: s.sessionId, text: "general" }));
assert.equal(res.status, 400);
// a surface that doesn't exist is a 404, not a silent session-level comment
const ghost = await app.request("/api/comments", json({ snippet: "missing", text: "ghost" }));
assert.equal(ghost.status, 404);
});
test("author=user reads resume from the agent's server-side cursor", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
await app.request("/api/comments", json({ snippet: s.id, text: "first", author: "user" }));
// no cursor given: delivered once...
const first = (await (
await app.request(`/api/comments?session=${s.sessionId}&author=user`)
).json()) as any;
assert.equal(first.comments.length, 1);
assert.equal(first.comments[0].text, "first");
// ...and not again on the next cursor-less read (e.g. a fresh CLI process)
const again = (await (
await app.request(`/api/comments?session=${s.sessionId}&author=user`)
).json()) as any;
assert.equal(again.comments.length, 0);
// unfiltered reads (the viewer) never consume the cursor
const viewer = (await (await app.request(`/api/comments?session=${s.sessionId}`)).json()) as any;
assert.equal(viewer.comments.length, 1);
});
test("piggyback delivery advances the cursor seen by author=user waits", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
await app.request("/api/comments", json({ snippet: s.id, text: "tweak it", author: "user" }));
// an agent write piggybacks the pending feedback...
const updated = (await (
await app.request(`/api/snippets/${s.id}`, {
...json({ html: "<p>v2</p>" }),
method: "PUT",
})
).json()) as any;
assert.equal(updated.userFeedback.length, 1);
assert.equal(updated.userFeedback[0].text, "tweak it");
// ...so a cursor-less wait on another channel must not re-deliver it
const wait = (await (
await app.request(`/api/comments?session=${s.sessionId}&author=user`)
).json()) as any;
assert.equal(wait.comments.length, 0);
});
test("author=user lastSeq reflects the last comment overall, not the last user comment", async () => {
// When an agent reply lands after the user comment, the cursor returned
// to the caller (lastSeq) must be the agent comment's seq — otherwise
// the next call re-reads the agent comment and wastes a round-trip.
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
await app.request("/api/comments", json({ snippet: s.id, text: "first", author: "user" }));
await app.request("/api/comments", json({ snippet: s.id, text: "reply", author: "agent" }));
const res = (await (
await app.request(`/api/comments?session=${s.sessionId}&author=user&after=0`)
).json()) as any;
assert.equal(res.comments.length, 1);
assert.equal(res.comments[0].text, "first");
// lastSeq is the agent comment's seq (2), not the user comment's (1)
assert.equal(res.lastSeq, 2);
});
function makeVersionApp(version?: string, latest?: { version: string; notes?: string } | Error) {
const dir = mkdtempSync(join(tmpdir(), "sideshow-test-"));
return createApp({
store: new JsonFileStore(join(dir, "data.json")),
viewerHtml: "<html>viewer</html>",
guideMarkdown: "# guide",
setupText: "# setup",
agentHowtoText: "# agent how-to",
version,
upgradeCommand: "npm install -g sideshow",
fetchLatestRelease: () =>
latest instanceof Error ? Promise.reject(latest) : Promise.resolve(latest ?? null),
});
}
test("version endpoint reports an available update with notes", async () => {
const app = makeVersionApp("0.3.0", { version: "0.4.0", notes: "### Added\n- things" });
const res = (await (await app.request("/api/version")).json()) as any;
assert.deepEqual(res, {
current: "0.3.0",
latest: "0.4.0",
updateAvailable: true,
upgradeCommand: "npm install -g sideshow",
notes: "### Added\n- things",
});
});
test("version endpoint is quiet when current, unconfigured, or offline", async () => {
// up to date — and a same-or-older registry version is never an "update"
const same = (await (
await makeVersionApp("0.4.0", { version: "0.4.0" }).request("/api/version")
).json()) as any;
assert.equal(same.updateAvailable, false);
assert.equal(same.upgradeCommand, null);
const older = (await (
await makeVersionApp("0.4.1", { version: "0.4.0" }).request("/api/version")
).json()) as any;
assert.equal(older.updateAvailable, false);
// no version configured: nothing to compare against
const none = (await (await makeVersionApp(undefined).request("/api/version")).json()) as any;
assert.deepEqual(none, { current: null, latest: null, updateAvailable: false });
// lookup failure is silent
const offline = (await (
await makeVersionApp("0.3.0", new Error("offline")).request("/api/version")
).json()) as any;
assert.deepEqual(offline, {
current: "0.3.0",
latest: null,
updateAvailable: false,
upgradeCommand: null,
notes: null,
});
});
test("long-poll resolves when a comment arrives", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
const pending = app.request(`/api/comments?session=${s.sessionId}&wait=5`);
setTimeout(() => {
app.request("/api/comments", json({ snippet: s.id, text: "feedback!", author: "user" }));
}, 50);
const start = Date.now();
const result = (await (await pending).json()) as any;
assert.equal(result.comments.length, 1);
assert.equal(result.comments[0].text, "feedback!");
assert.ok(Date.now() - start < 4000, "should resolve well before the timeout");
});
// --- connection caps (SSE + long-poll share one per-instance bound) ---
test("SSE connections are capped; a released slot lets a new one in", async () => {
const app = makeApp(undefined, { maxHoldConnections: 2 });
const controllers = [new AbortController(), new AbortController()];
// Two streams fill the cap. The slot is acquired before streamSSE opens, so
// merely having the Response back means it's held — no body read needed.
const streams = await Promise.all(
controllers.map((ac) => app.request("/api/events", { signal: ac.signal })),
);
assert.ok(streams.every((s) => s.status === 200));
// A third is rejected.
assert.equal((await app.request("/api/events")).status, 503);
// Releasing one frees a slot for a fresh stream.
controllers[0].abort();
await streams[0].body!.cancel().catch(() => undefined);
await new Promise((resolve) => setTimeout(resolve, 30));
const again = await app.request("/api/events", { signal: new AbortController().signal });
assert.equal(again.status, 200);
// cleanup
controllers[1].abort();
await streams[1].body!.cancel().catch(() => undefined);
await again.body!.cancel().catch(() => undefined);
});
test("long-poll waits count against the hold cap; instant reads do not", async () => {
const app = makeApp(undefined, { maxHoldConnections: 2 });
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
// Two held long-polls fill the cap; they resolve when a comment lands.
const pending = [
app.request(`/api/comments?session=${s.sessionId}&wait=5`),
app.request(`/api/comments?session=${s.sessionId}&wait=5`),
];
await new Promise((resolve) => setTimeout(resolve, 30));
// A third held wait is rejected.
assert.equal((await app.request(`/api/comments?session=${s.sessionId}&wait=5`)).status, 503);
// An instant (?wait=0) read is not a held connection — still served at cap.
assert.equal((await app.request(`/api/comments?session=${s.sessionId}`)).status, 200);
// Post a comment so both held waits resolve and release their slots.
await app.request("/api/comments", json({ snippet: s.id, text: "release" }));
const resolved = await Promise.all(pending);
assert.ok(resolved.every((r) => r.status === 200));
});
test("SSE and long-poll share the same connection budget", async () => {
const app = makeApp(undefined, { maxHoldConnections: 2 });
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
// One SSE + one long-poll fills the shared cap.
const sse = await app.request("/api/events", { signal: new AbortController().signal });
assert.equal(sse.status, 200);
const poll = app.request(`/api/comments?session=${s.sessionId}&wait=5`);
await new Promise((resolve) => setTimeout(resolve, 30));
// Neither a second SSE nor a second long-poll fits.
assert.equal((await app.request("/api/events")).status, 503);
assert.equal((await app.request(`/api/comments?session=${s.sessionId}&wait=5`)).status, 503);
// Releasing the long-poll (comment lands) frees a slot for SSE again.
await app.request("/api/comments", json({ snippet: s.id, text: "release" }));
await poll;
const sseAgain = await app.request("/api/events", { signal: new AbortController().signal });
assert.equal(sseAgain.status, 200);
// cleanup
await sse.body!.cancel().catch(() => undefined);
await sseAgain.body!.cancel().catch(() => undefined);
});
test("deleting a session cascades to snippets and comments", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
await app.request("/api/comments", json({ snippet: s.id, text: "hi" }));
const res = await app.request(`/api/sessions/${s.sessionId}`, { method: "DELETE" });
assert.equal(res.status, 200);
assert.equal((await app.request(`/api/snippets/${s.id}`)).status, 404);
const sessions = (await (await app.request("/api/sessions")).json()) as any;
assert.equal(sessions.length, 0);
});
test("rename session", async () => {
const app = makeApp();
const s = (await (await app.request("/api/snippets", json({ html: "<p>x</p>" }))).json()) as any;
const res = await app.request(`/api/sessions/${s.sessionId}`, {
...json({ title: "Auth refactor" }),
method: "PATCH",
});
assert.equal(((await res.json()) as any).title, "Auth refactor");
});
test("auth hook can guard an embedding host without authToken", async () => {
const dir = mkdtempSync(join(tmpdir(), "sideshow-test-"));
const app = createApp({
store: new JsonFileStore(join(dir, "data.json")),
viewerHtml: "<html>viewer</html>",
guideMarkdown: "# guide",
setupText: "# setup",
authenticate: (request) => request.headers.get("x-sideshow-internal") === "ok",
});
assert.equal((await app.request("/guide")).status, 401);
assert.equal((await app.request("/api/sessions")).status, 401);
const allowed = await app.request("/api/sessions", { headers: { "x-sideshow-internal": "ok" } });
assert.equal(allowed.status, 200);
});
test("auth token guards mutating routes when configured", async () => {
const app = makeApp("secret");
const denied = await app.request("/api/snippets", json({ html: "<p>x</p>" }));
assert.equal(denied.status, 401);
const allowed = await app.request("/api/snippets", authedJson({ html: "<p>x</p>" }));
assert.equal(allowed.status, 201);
// full surface is guarded, including reads and the viewer
assert.equal((await app.request("/api/sessions")).status, 401);
assert.equal((await app.request("/")).status, 401);
// docs and bootstrap instructions stay open
assert.equal((await app.request("/guide")).status, 200);
assert.equal((await app.request("/setup")).status, 200);
assert.equal((await app.request("/agent-howto")).status, 200);
// ?key= grants access and sets a cookie for subsequent requests
const keyed = await app.request("/?key=secret");
assert.equal(keyed.status, 200);
const cookie = keyed.headers.get("set-cookie") ?? "";
assert.ok(cookie.includes("sideshow_key=secret"));
const viaCookie = await app.request("/api/sessions", {
headers: { cookie: "sideshow_key=secret" },
});
assert.equal(viaCookie.status, 200);
});
async function readSseUntil(res: Response, needle: string, abort?: () => void): Promise<string> {
assert.ok(res.body);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let text = "";
try {
await Promise.race([
(async () => {
while (!text.includes(needle)) {
const chunk = await reader.read();
if (chunk.done) break;
text += decoder.decode(chunk.value, { stream: true });
}
})(),
new Promise<void>((_, reject) =>
setTimeout(() => reject(new Error(`timed out waiting for ${needle}`)), 1000),
),
]);
} finally {
abort?.();
await reader.cancel().catch(() => undefined);
}
return text;
}
// --- public read auth modes ---
test("public read full mode allows unauthenticated GETs but not writes", async () => {
const app = makeApp("secret", { publicRead: "full" });
assert.equal((await app.request("/")).status, 200);
assert.equal((await app.request("/session/anything")).status, 200);
assert.equal((await app.request("/api/sessions")).status, 200);
assert.equal((await app.request("/api/theme")).status, 200);
assert.equal((await app.request("/api/version")).status, 200);
const created = (await (
await app.request("/api/snippets", authedJson({ html: "<p>x</p>" }))
).json()) as any;
assert.equal((await app.request(`/s/${created.id}`)).status, 200);
assert.equal((await app.request(`/api/surfaces/${created.id}`)).status, 200);
assert.equal((await app.request("/api/snippets", json({ html: "<p>x</p>" }))).status, 401);
assert.equal((await app.request("/api/comments", json({ text: "hi" }))).status, 401);
});