@crossworks/share-ui 0.300.143 → 0.400.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crossworks/share-ui",
3
- "version": "0.300.143",
3
+ "version": "0.400.0",
4
4
  "description": "The server-rendered share surface — the /s/<token> presenters, view-payload contract, mini-app sandbox, and the few primitives they need. Lives in MANTLE (the server renders these), published for jackdaw to consume; may depend only on @mantle/{client-types,content-core} (the jackdaw-repo-split boundary).",
5
5
  "type": "module",
6
6
  "exports": {
@@ -16,7 +16,9 @@
16
16
  "./view-payload": "./src/view-payload.ts",
17
17
  "./heading-fold-dom": "./src/heading-fold-dom.ts",
18
18
  "./app-sandbox": "./src/app-sandbox.tsx",
19
+ "./canvas-sandbox": "./src/canvas-sandbox.tsx",
19
20
  "./app-frame-html": "./src/app-frame-html.ts",
21
+ "./canvas-frame-html": "./src/canvas-frame-html.ts",
20
22
  "./app-bridge-protocol": "./src/app-bridge-protocol.ts",
21
23
  "./ui/button": "./src/ui/button.tsx",
22
24
  "./ui/input": "./src/ui/input.tsx",
@@ -27,8 +29,8 @@
27
29
  "./nav-items": "./src/nav-items.ts",
28
30
  "./help-topics": "./src/help-topics.ts",
29
31
  "./appearance": "./src/appearance.ts",
30
- "./neat-background": "./src/neat-background.ts",
31
- "./neat-mount": "./src/neat-mount.ts",
32
+ "./drift": "./src/drift/index.ts",
33
+ "./drift-mount": "./src/drift-mount.ts",
32
34
  "./share-mode": "./src/share-mode.ts",
33
35
  "./backgrounds": "./src/backgrounds.ts",
34
36
  "./avatar": "./src/avatar.ts",
@@ -39,14 +41,13 @@
39
41
  "dependencies": {
40
42
  "@dicebear/core": "^10.7.0",
41
43
  "@dicebear/styles": "^10.6.0",
42
- "@firecms/neat": "1.1.0",
43
- "@mantle/client-types": "npm:@crossworks/client-types@0.300.143",
44
- "@mantle/content-core": "npm:@crossworks/content-core@0.300.143",
44
+ "@mantle/client-types": "npm:@crossworks/client-types@0.400.0",
45
+ "@mantle/content-core": "npm:@crossworks/content-core@0.400.0",
45
46
  "@radix-ui/react-label": "^2.1.16",
46
47
  "@radix-ui/react-slot": "^1.4.0",
47
48
  "class-variance-authority": "^0.7.1",
48
49
  "clsx": "^2.1.1",
49
- "katex": "^0.19.0",
50
+ "katex": "0.19.1",
50
51
  "lucide-react": "^1.52.0",
51
52
  "react-markdown": "^10.1.0",
52
53
  "remark-gfm": "^4.0.1",
@@ -52,7 +52,7 @@ describe('buildAppFrameHtml — error reporting', () => {
52
52
 
53
53
  describe('buildAppFrameHtml — the Neat backdrop', () => {
54
54
  const SPEC = '{"v":1,"seed":42,"tone":"auto","speed":2}';
55
- const withNeat = (neatLicense?: string | null) =>
55
+ const withNeat = () =>
56
56
  buildAppFrameHtml({
57
57
  bundleCode: 'console.log(1)',
58
58
  appCss: '',
@@ -61,7 +61,6 @@ describe('buildAppFrameHtml — the Neat backdrop', () => {
61
61
  colorTheme: 'darkmatter',
62
62
  viewport: true,
63
63
  neatSpec: SPEC,
64
- neatLicense,
65
64
  });
66
65
 
67
66
  it('renders no host div and no runtime script without a spec', () => {
@@ -77,6 +76,9 @@ describe('buildAppFrameHtml — the Neat backdrop', () => {
77
76
  expect(html).toContain('src="/share-runtime/share-page.js"');
78
77
  // No reader attribute — the runtime must never mount its toggle in a frame.
79
78
  expect(html).not.toContain('data-share-mode-default');
79
+ // No surface attribute: an app's own text sits on the gradient, so every
80
+ // frame paints the floored 'app' look (readDriftSurface's default).
81
+ expect(html).not.toContain('data-drift-surface');
80
82
  });
81
83
 
82
84
  it('keeps html transparent so the body ground propagates BENEATH the canvas', () => {
@@ -90,11 +92,6 @@ describe('buildAppFrameHtml — the Neat backdrop', () => {
90
92
  expect(html).not.toContain('<body class="bg-background');
91
93
  });
92
94
 
93
- it('carries the licence only when set', () => {
94
- expect(withNeat('k-1')).toContain('data-neat-license="k-1"');
95
- expect(withNeat()).not.toContain('data-neat-license');
96
- });
97
-
98
95
  it('makes --card translucent over a Neat ground, and ONLY then', () => {
99
96
  // The derived token sits on :root and the override on body — a custom
100
97
  // property may not reference itself on the same element. No spec ⇒ no
@@ -27,7 +27,8 @@ import type { AppViewer } from '@mantle/client-types/app-viewer';
27
27
  * attachments. The document's origin is OPAQUE (sandboxed), so CSP `'self'`
28
28
  * is unreliable here — every source names the host origin explicitly:
29
29
  * scripts only from `/app-runtime/` (the shared React/kit/host runtime the
30
- * import map points at), styles/fonts only from `/share-runtime/` (the
30
+ * import map points at) and `/canvas-runtime/` (the vendored libraries the
31
+ * same map names), styles/fonts only from `/share-runtime/` (the
31
32
  * self-contained stylesheet the frame links) and `/fonts/` (owner font
32
33
  * library). */
33
34
  export function buildAppFrameCsp(origin: string): string {
@@ -40,10 +41,15 @@ export function buildAppFrameCsp(origin: string): string {
40
41
  // inside the AppSandbox iframe it composes with the identical attribute.
41
42
  `sandbox allow-scripts; ` +
42
43
  `default-src 'none'; style-src 'unsafe-inline' ${origin}/share-runtime/; ` +
43
- // share-runtime scripts joined app-runtime for the Neat backdrop
44
+ // share-runtime scripts joined app-runtime for the Drift backdrop
44
45
  // (share-page.js + its lazy WebGL chunk) — same-origin built assets,
45
- // no new capability.
46
- `script-src 'unsafe-inline' ${origin}/app-runtime/ ${origin}/share-runtime/; ` +
46
+ // no new capability. canvas-runtime joined for the vendored libraries an
47
+ // app may import (echarts, d3, three, konva, katex, the diagram
48
+ // templates; app-build app-libraries.ts): the same content-hashed files
49
+ // a Present canvas loads, on the brain origin. No 'unsafe-eval' (the one
50
+ // library that needs it, Alpine.js, is left out of apps), and
51
+ // connect-src stays 'none', so a library adds no way out.
52
+ `script-src 'unsafe-inline' ${origin}/app-runtime/ ${origin}/share-runtime/ ${origin}/canvas-runtime/; ` +
47
53
  `img-src data: blob: ${origin}; ` +
48
54
  `font-src data: ${origin}/share-runtime/ ${origin}/fonts/; ` +
49
55
  "connect-src 'none'; base-uri 'none'; form-action 'none'"
@@ -150,14 +156,11 @@ export function buildAppFrameHtml(opts: {
150
156
  colorTheme: string | null;
151
157
  /** Viewport frame (iframe IS the viewport) vs card frame (auto-sized). */
152
158
  viewport: boolean;
153
- /** The brain's saved Neat background spec (canonical encoding), or
159
+ /** The brain's saved background spec (Drift; canonical encoding), or
154
160
  * null/absent for the plain themed ground. Resolved server-side by the
155
161
  * frame route — owner frames from the prefs alone, shared frames gated by
156
162
  * the shareNeat switch. */
157
163
  neatSpec?: string | null;
158
- /** Neat licence key for watermark removal — same env-sourced value the
159
- * other surfaces ride. */
160
- neatLicense?: string | null;
161
164
  /** Who runs the app (host.me()); null/absent bakes nothing and host.me()
162
165
  * rejects. Never email: the type has no such field. */
163
166
  viewer?: AppViewer | null;
@@ -227,7 +230,7 @@ ${
227
230
  </head>
228
231
  <body class="text-foreground">
229
232
  ${
230
- /* The brain's saved Neat gradient, rendered INSIDE the frame document —
233
+ /* The brain's saved Drift background, rendered INSIDE the frame document —
231
234
  the iframe is opaque-origin (sandbox without allow-same-origin), so
232
235
  transparency renders WHITE and the host page's backdrop can never show
233
236
  through; the only way the background "transfers" into an app is to
@@ -236,11 +239,11 @@ ${
236
239
  data-share-mode-default, which frames deliberately lack), and the
237
240
  runtime's class observer repaints it when the parent posts a theme
238
241
  change. z-index:-1 sits above the html ground (the canvas layer) and
239
- below all app content. */
242
+ below all app content. No data-drift-surface, deliberately: an app's own
243
+ text sits right on the gradient, so every frame, owner or shared, paints
244
+ the floored 'app' look (DriftSurface in drift/spec.ts). */
240
245
  opts.neatSpec
241
- ? `<div data-neat-spec="${attr(opts.neatSpec)}"${
242
- opts.neatLicense ? ` data-neat-license="${attr(opts.neatLicense)}"` : ''
243
- } style="position:fixed;inset:0;z-index:-1;pointer-events:none" aria-hidden="true"></div>\n`
246
+ ? `<div data-neat-spec="${attr(opts.neatSpec)}" style="position:fixed;inset:0;z-index:-1;pointer-events:none" aria-hidden="true"></div>\n`
244
247
  : ''
245
248
  }<div id="root"></div>
246
249
  <script>${ERROR_REPORTER}</script>
@@ -8,7 +8,7 @@ import {
8
8
  DEFAULT_COLOR_THEME,
9
9
  FRESH_COLOR_THEME,
10
10
  } from './lib/themes';
11
- import { decodeNeatSpec, encodeNeatSpec } from './neat-background';
11
+ import { decodeDriftSpec } from './drift/spec';
12
12
 
13
13
  /**
14
14
  * The client fallbacks for the fresh-install look agree with the brain's
@@ -36,10 +36,10 @@ describe('the fresh-install look exists', () => {
36
36
  expect(AVATAR_PICKER_STYLES.map((s) => s.id)).toContain(FRESH_APPEARANCE.avatarStyle);
37
37
  });
38
38
 
39
- it('carries a Neat spec in canonical form', () => {
40
- const spec = decodeNeatSpec(FRESH_APPEARANCE.neatBackground);
39
+ it('carries a background spec that decodes (a Neat v1 spec, painted as silk)', () => {
40
+ const spec = decodeDriftSpec(FRESH_APPEARANCE.neatBackground);
41
41
  expect(spec).not.toBeNull();
42
- expect(encodeNeatSpec(spec!)).toBe(FRESH_APPEARANCE.neatBackground);
42
+ expect(spec?.style).toBe('silk');
43
43
  });
44
44
  });
45
45
 
package/src/appearance.ts CHANGED
@@ -58,8 +58,8 @@ export type BrainAppearance = {
58
58
  avatarStyle: string | null;
59
59
  avatarTint: string | null;
60
60
  backgrounds: string | null;
61
- /** The generated whole-surface Neat gradient's spec, compact JSON
62
- * `{v,seed,tone,speed}` — colours derive from the live theme client-side.
61
+ /** The generated whole-surface background's spec (Drift), compact JSON,
62
+ * v2 or a Neat-era v1 (decodeDriftSpec reads both); colours derive from the live theme client-side.
63
63
  * NOT stamped onto `<html>`: it feeds a WebGL component, not the CSS.
64
64
  * Optional for the published-contract reason below: readers treat absence
65
65
  * as "not set" and paint the plain themed fill. */
@@ -72,8 +72,8 @@ export type BrainAppearance = {
72
72
  * the published-contract reason below; absence reads as 'light', the share
73
73
  * surface's historical rendering. */
74
74
  defaultMode?: string | null;
75
- /** Whether shared surfaces (/s, the team workspace) paint the saved Neat
76
- * gradient at all — false is the printable plain fallback. NOT stamped onto
75
+ /** Whether shared surfaces (/s, the team workspace) paint the saved Drift
76
+ * background at all — false is the printable plain fallback. NOT stamped onto
77
77
  * `<html>`; readers treat absence as true (the default). */
78
78
  shareNeat?: boolean | null;
79
79
  /**
@@ -0,0 +1,207 @@
1
+ import { runInNewContext } from 'node:vm';
2
+ import { describe, expect, it } from 'vitest';
3
+ import {
4
+ buildCanvasEmbedCsp,
5
+ buildCanvasFrameCsp,
6
+ buildCanvasFrameHtml,
7
+ } from './canvas-frame-html';
8
+
9
+ const ORIGIN = 'https://brain.example.test';
10
+
11
+ describe('buildCanvasFrameCsp', () => {
12
+ const csp = buildCanvasFrameCsp(ORIGIN, ['https://app.example.test']);
13
+ const directives = new Map(
14
+ csp.split(';').map((d) => {
15
+ const [name, ...values] = d.trim().split(/\s+/);
16
+ return [name, values.join(' ')] as const;
17
+ }),
18
+ );
19
+
20
+ it('sandboxes the document and closes every network door', () => {
21
+ expect(directives.get('sandbox')).toBe('allow-scripts');
22
+ expect(directives.get('default-src')).toBe("'none'");
23
+ expect(directives.get('connect-src')).toBe("'none'");
24
+ expect(directives.get('frame-src')).toBe("'none'");
25
+ expect(directives.get('form-action')).toBe("'none'");
26
+ expect(directives.get('base-uri')).toBe("'none'");
27
+ });
28
+
29
+ it('loads script only inline and from the vendored runtime', () => {
30
+ expect(directives.get('script-src')).toBe(
31
+ `'unsafe-inline' 'unsafe-eval' ${ORIGIN}/canvas-runtime/`,
32
+ );
33
+ });
34
+
35
+ it('never lists the brain origin for images or media: no GET at our own API', () => {
36
+ expect(directives.get('img-src')).toBe('data: blob:');
37
+ expect(directives.get('media-src')).toBe('data: blob:');
38
+ });
39
+
40
+ it('is framed only by the brain and the named owner UI origins', () => {
41
+ expect(directives.get('frame-ancestors')).toBe(`${ORIGIN} https://app.example.test`);
42
+ });
43
+ });
44
+
45
+ describe('buildCanvasFrameHtml', () => {
46
+ const base = {
47
+ source: '<!DOCTYPE html><html><head><title>T</title></head><body>hi</body></html>',
48
+ css: '.p-6{padding:1.5rem}',
49
+ importMapJson: '{"imports":{"d3":"/canvas-runtime/d3-AAAAAAAA.js"}}',
50
+ cls: 'dark',
51
+ colorTheme: 'ocean',
52
+ size: { w: 1600, h: 900 } as const,
53
+ theme: 'follow' as const,
54
+ fontCss: '@font-face{font-family:"X"}',
55
+ };
56
+
57
+ it('puts the import map and prelude before the canvas, with one doctype', () => {
58
+ const html = buildCanvasFrameHtml(base);
59
+ expect(html.startsWith('<!doctype html>\n')).toBe(true);
60
+ expect(html.match(/<!doctype/gi)).toHaveLength(1);
61
+ expect(html.indexOf('type="importmap"')).toBeLessThan(html.indexOf('<html>'));
62
+ expect(html).toContain('/canvas-runtime/d3-AAAAAAAA.js');
63
+ expect(html).toContain('.p-6{padding:1.5rem}');
64
+ expect(html).toContain('width:1600px!important');
65
+ });
66
+
67
+ it('bakes the theme in as JSON a value cannot break out of', () => {
68
+ const html = buildCanvasFrameHtml({ ...base, cls: '</script><script>alert(1)</script>' });
69
+ expect(html).not.toContain('</script><script>alert(1)');
70
+ expect(html).toContain('\\u003c/script>');
71
+ });
72
+
73
+ it('a fixed-theme canvas ignores the host theme', () => {
74
+ const html = buildCanvasFrameHtml({ ...base, theme: 'fixed' });
75
+ expect(html).toContain('"cls":""');
76
+ expect(html).toContain('"ct":null');
77
+ expect(html).toContain('"follow":false');
78
+ });
79
+
80
+ it('a fill canvas gets the whole viewport, no letterbox', () => {
81
+ const html = buildCanvasFrameHtml({ ...base, size: 'fill' });
82
+ expect(html).not.toContain('--canvas-scale,1');
83
+ expect(html).toContain('"size":null');
84
+ });
85
+
86
+ it('keeps CSS from closing its style tag', () => {
87
+ const html = buildCanvasFrameHtml({ ...base, css: '.a{content:"</style><script>"}' });
88
+ expect(html).not.toContain('</style><script>');
89
+ });
90
+ });
91
+
92
+ describe('stripLeadingDoctype', () => {
93
+ it('drops a leading BOM and doctype, keeping comments before it', async () => {
94
+ const { stripLeadingDoctype } = await import('./canvas-frame-html');
95
+ expect(stripLeadingDoctype('<!DOCTYPE html><html>')).toBe('<html>');
96
+ expect(stripLeadingDoctype('<!-- a --> <!doctype html><html>')).toBe('<!-- a --> <html>');
97
+ expect(stripLeadingDoctype('<html><!doctype html>')).toBe('<html><!doctype html>');
98
+ });
99
+
100
+ it('is linear: many comments and no doctype take no time (the audit ReDoS)', async () => {
101
+ const { stripLeadingDoctype } = await import('./canvas-frame-html');
102
+ const evil = '<!--a-->'.repeat(50_000) + '<html>';
103
+ const t = performance.now();
104
+ expect(stripLeadingDoctype(evil)).toBe(evil);
105
+ expect(performance.now() - t).toBeLessThan(200);
106
+ });
107
+ });
108
+
109
+ describe('the prelude', () => {
110
+ it('takes WebRTC away before any canvas script runs', () => {
111
+ const html = buildCanvasFrameHtml({
112
+ source: '<html><body><script>new RTCPeerConnection()</script></body></html>',
113
+ css: '',
114
+ importMapJson: '{"imports":{}}',
115
+ cls: '',
116
+ colorTheme: null,
117
+ size: 'fill',
118
+ theme: 'follow',
119
+ fontCss: '',
120
+ });
121
+ expect(html.indexOf("'RTCPeerConnection'")).toBeGreaterThan(0);
122
+ expect(html.indexOf("'RTCPeerConnection'")).toBeLessThan(html.indexOf('new RTCPeerConnection'));
123
+ });
124
+
125
+ it('holds the nonce in its closure, posts it with ready, and removes its own script', () => {
126
+ const html = buildCanvasFrameHtml({
127
+ source: '<html><body>x</body></html>',
128
+ css: '',
129
+ importMapJson: '{"imports":{}}',
130
+ cls: '',
131
+ colorTheme: null,
132
+ size: 'fill',
133
+ theme: 'follow',
134
+ fontCss: '',
135
+ nonce: 'abc123',
136
+ });
137
+ const prelude = html.slice(0, html.indexOf('<html>'));
138
+ expect(prelude).toContain('"n":"abc123"');
139
+ expect(prelude).toContain('document.currentScript');
140
+ expect(prelude).toContain("kind:'ready',n:nonce");
141
+ // The canvas's own text never holds it.
142
+ expect(html.slice(html.indexOf('<html>'))).not.toContain('abc123');
143
+ });
144
+
145
+ it('a canvas that replaces window.parent cannot obtain the nonce (the re-audit R1)', () => {
146
+ const html = buildCanvasFrameHtml({
147
+ source: '<html><body>x</body></html>',
148
+ css: '',
149
+ importMapJson: '{"imports":{}}',
150
+ cls: '',
151
+ colorTheme: null,
152
+ size: 'fill',
153
+ theme: 'follow',
154
+ fontCss: '',
155
+ nonce: 'secret-nonce',
156
+ });
157
+ const prelude = /<script>(\(function\(\)\{[\s\S]*?\}\)\(\);)<\/script>/.exec(html)![1]!;
158
+ // A window as far as the prelude reads one: the real parent another
159
+ // origin's, its postMessage out of the canvas's reach.
160
+ const toParent: unknown[] = [];
161
+ const stolen: unknown[] = [];
162
+ const handlers: Record<string, Array<(e: unknown) => void>> = {};
163
+ const el = {
164
+ className: '',
165
+ setAttribute() {},
166
+ removeAttribute() {},
167
+ style: { setProperty() {} },
168
+ };
169
+ const win: Record<string, unknown> = {
170
+ parent: Object.freeze({ postMessage: (m: unknown) => toParent.push(m) }),
171
+ addEventListener: (k: string, f: (e: unknown) => void) => (handlers[k] ??= []).push(f),
172
+ innerWidth: 800,
173
+ innerHeight: 600,
174
+ };
175
+ const document = { currentScript: null, documentElement: el };
176
+ const ctx = { window: win, document, Object, String, Math };
177
+ runInNewContext(prelude, ctx);
178
+ // The canvas runs after the prelude: it swaps the parent for its own.
179
+ runInNewContext(
180
+ 'window.parent = { postMessage: function (m) { stolen.push(m); } };',
181
+ Object.assign(ctx, { stolen }),
182
+ );
183
+ for (const f of handlers.load ?? []) f({});
184
+ for (const f of handlers.error ?? []) f({ message: 'boom' });
185
+ expect(stolen).toEqual([]);
186
+ expect(toParent).toEqual([
187
+ { v: 1, kind: 'ready', n: 'secret-nonce' },
188
+ { v: 1, kind: 'error', message: 'boom' },
189
+ ]);
190
+ // A theme message from the canvas's fake parent is not the parent's.
191
+ const fake = win.parent;
192
+ for (const f of handlers.message ?? [])
193
+ f({ source: fake, data: { v: 1, kind: 'theme', cls: 'x' } });
194
+ expect(el.className).toBe('');
195
+ });
196
+ });
197
+
198
+ describe('buildCanvasEmbedCsp', () => {
199
+ it('requires no network of whatever loads in the frame, and names only what an embedder may', () => {
200
+ const csp = buildCanvasEmbedCsp('https://brain.example');
201
+ expect(csp).toContain("connect-src 'none'");
202
+ expect(csp).toContain("form-action 'none'");
203
+ expect(csp).toContain('https://brain.example/canvas-runtime/');
204
+ expect(csp).not.toContain('sandbox');
205
+ expect(csp).not.toContain('frame-ancestors');
206
+ });
207
+ });
@@ -0,0 +1,257 @@
1
+ /**
2
+ * The Present canvas FRAME document: what a sandboxed iframe navigates to
3
+ * (GET /api/presents/[id]/frame, docs/proposals/canvas-files.md section 5.2).
4
+ * Pure string building, served by the brain, as the mini-app frame
5
+ * (./app-frame-html.ts) is, minus the bridge: a canvas gets no database, no
6
+ * tools and no network. It is presentation only.
7
+ *
8
+ * The canvas is the agent's own whole HTML document. The frame puts a short
9
+ * PRELUDE before it (after the doctype): the import map, the theme, fonts and
10
+ * kit stylesheets, the compiled Tailwind utilities, the fit, and the error
11
+ * and ready reporters. Everything in the prelude is head content, so the
12
+ * parser stays in the head and the canvas's own `<html>` and `<head>` tags
13
+ * merge into the same document. Being first is what makes the import map
14
+ * apply to every module script the canvas writes.
15
+ *
16
+ * Nothing here is a security boundary on its own. The boundary is the
17
+ * response's CSP header (buildCanvasFrameCsp) and the iframe's
18
+ * `sandbox="allow-scripts"`: an opaque origin, no cookies or storage, no
19
+ * fetch, no form posts, no popups, no top navigation.
20
+ */
21
+ import type { CanvasSize } from '@mantle/content-core/canvas';
22
+
23
+ /**
24
+ * The canvas frame CSP, sent as a HEADER (section 5.2). Every source names
25
+ * the brain origin explicitly: the document's origin is opaque, so `'self'`
26
+ * would not mean the brain.
27
+ *
28
+ * - `sandbox allow-scripts`: the document is sandboxed however it is
29
+ * reached, even opened directly in a tab.
30
+ * - Scripts: inline (the canvas IS inline script) and `'unsafe-eval'` for
31
+ * Alpine.js's attribute expressions (section 6.1), plus the vendored
32
+ * runtime only. No other host.
33
+ * - `img-src` and `media-src` are inline only: unlike an app frame, the brain
34
+ * origin is NOT listed, so a canvas cannot even fire a GET at our own API.
35
+ * - `connect-src 'none'`, `frame-src 'none'`, `form-action 'none'`,
36
+ * `base-uri 'none'`: no fetch, XHR, WebSocket, beacon, nested frame or
37
+ * post.
38
+ * - `frame-ancestors`: only the brain and the owner UI origins may frame it.
39
+ * - Workers: blob workers in a live frame; none in a render (`workers:
40
+ * false`), where a worker's console would reach the renderer past the
41
+ * page's caps. No library of the runtime needs one (Plotly only for its
42
+ * map tiles, which need the network).
43
+ */
44
+ export function buildCanvasFrameCsp(
45
+ origin: string,
46
+ frameAncestors: readonly string[],
47
+ opts: { workers?: boolean } = {},
48
+ ): string {
49
+ const ancestors = [...new Set([origin, ...frameAncestors])].join(' ');
50
+ return (
51
+ 'sandbox allow-scripts; ' +
52
+ "default-src 'none'; " +
53
+ `script-src 'unsafe-inline' 'unsafe-eval' ${origin}/canvas-runtime/; ` +
54
+ `style-src 'unsafe-inline' ${origin}/canvas-runtime/ ${origin}/share-runtime/; ` +
55
+ 'img-src data: blob:; ' +
56
+ `font-src data: ${origin}/canvas-runtime/ ${origin}/share-runtime/ ${origin}/fonts/ ${origin}/Inter/; ` +
57
+ 'media-src data: blob:; ' +
58
+ "connect-src 'none'; " +
59
+ "frame-src 'none'; " +
60
+ (opts.workers === false ? "worker-src 'none'; " : 'worker-src blob:; ') +
61
+ "base-uri 'none'; " +
62
+ "form-action 'none'; " +
63
+ `frame-ancestors ${ancestors}`
64
+ );
65
+ }
66
+
67
+ /**
68
+ * The CSP the PARENT requires of whatever loads in a canvas iframe (CSP
69
+ * embedded enforcement: the iframe's `csp` attribute, canvas-sandbox.tsx).
70
+ * The frame document's own header already says all of this and more; what
71
+ * this adds is for a page the canvas navigated its frame to: unless that
72
+ * page answers `Allow-CSP-From`, the browser does not load it, and if it
73
+ * does, it runs under these rules (no network, no forms). The directives an
74
+ * embedder may not require (sandbox, frame-ancestors) are left out.
75
+ * Chromium enforces it (the desktop app is Chromium); elsewhere the other
76
+ * layers stand (the ready proof, the navigation guard).
77
+ */
78
+ export function buildCanvasEmbedCsp(origin: string): string {
79
+ return (
80
+ "default-src 'none'; " +
81
+ `script-src 'unsafe-inline' 'unsafe-eval' ${origin}/canvas-runtime/; ` +
82
+ `style-src 'unsafe-inline' ${origin}/canvas-runtime/ ${origin}/share-runtime/; ` +
83
+ 'img-src data: blob:; ' +
84
+ `font-src data: ${origin}/canvas-runtime/ ${origin}/share-runtime/ ${origin}/fonts/ ${origin}/Inter/; ` +
85
+ 'media-src data: blob:; ' +
86
+ "connect-src 'none'; " +
87
+ "frame-src 'none'; " +
88
+ 'worker-src blob:; ' +
89
+ "base-uri 'none'; " +
90
+ "form-action 'none'"
91
+ );
92
+ }
93
+
94
+ /** JSON for an inline script: `<` and the two JS line separators escaped, so
95
+ * no value can close the tag. */
96
+ function scriptJson(value: unknown): string {
97
+ return JSON.stringify(value)
98
+ .replace(/</g, '\\u003c')
99
+ .replace(/\u2028/g, '\\u2028')
100
+ .replace(/\u2029/g, '\\u2029');
101
+ }
102
+
103
+ /** Keep CSS text from closing its `<style>` tag (markup hygiene; the canvas
104
+ * runs its own script in this frame anyway). */
105
+ function styleText(css: string): string {
106
+ return css.replace(/<\//g, '<\\/');
107
+ }
108
+
109
+ /**
110
+ * Theme, fit, ready and error, in one classic inline script that runs while
111
+ * the head parses, before the canvas's own scripts.
112
+ *
113
+ * - WebRTC: removed before any canvas script runs. Its ICE traffic (a STUN
114
+ * host of the canvas's choice) is not under `connect-src` in Chromium, so
115
+ * it would be a way out; a canvas has no use for it, and the frame has no
116
+ * nested frame or other realm to take it back from.
117
+ * - Theme: the `<html>` class and data-color-theme are set at once (no flash),
118
+ * then follow the parent's `{v:1, kind:'theme'}` messages. A fixed-theme
119
+ * canvas ignores them.
120
+ * - Fit: a fixed design size scales to the frame with letterboxing (body
121
+ * transformed from its top left corner, recomputed on resize). `fill`
122
+ * leaves the layout to the canvas.
123
+ * - Ready and error: `{v:1, kind:'ready'}` on load, and every uncaught error
124
+ * or rejection as `{v:1, kind:'error', message}` (deduplicated), so the
125
+ * host can tell a broken canvas from a slow one. The parent checks
126
+ * `e.source` and accepts nothing else.
127
+ */
128
+ function preludeScript(opts: {
129
+ cls: string;
130
+ colorTheme: string | null;
131
+ followTheme: boolean;
132
+ size: CanvasSize;
133
+ nonce: string;
134
+ }): string {
135
+ const cfg = scriptJson({
136
+ cls: opts.cls,
137
+ ct: opts.colorTheme,
138
+ follow: opts.followTheme,
139
+ size: opts.size === 'fill' ? null : opts.size,
140
+ n: opts.nonce,
141
+ });
142
+ // The script takes itself out of the document as it runs: the nonce lives
143
+ // on only in this closure, out of the canvas's reach (it runs later, in the
144
+ // same document, and could otherwise read the script's text). The parent
145
+ // is read once, first: `window.parent` is replaceable, and a canvas that
146
+ // set it to an object of its own would be handed the nonce at load. The
147
+ // real parent is another origin's window, whose postMessage a canvas
148
+ // cannot change.
149
+ return `(function(){
150
+ var P=window.parent;
151
+ var me=document.currentScript;if(me&&me.parentNode){me.parentNode.removeChild(me);}
152
+ var cfg=${cfg};var h=document.documentElement;var nonce=cfg.n;cfg.n='';
153
+ ['RTCPeerConnection','webkitRTCPeerConnection','RTCDataChannel','RTCIceCandidate','RTCSessionDescription'].forEach(function(n){
154
+ try{Object.defineProperty(window,n,{value:undefined,writable:false,configurable:false});}catch(_){}});
155
+ function theme(cls,ct){h.className=cls||'';if(ct){h.setAttribute('data-color-theme',ct);}else{h.removeAttribute('data-color-theme');}}
156
+ theme(cfg.cls,cfg.ct);
157
+ window.addEventListener('message',function(e){
158
+ if(e.source!==P)return;var m=e.data;if(!m||m.v!==1)return;
159
+ if(m.kind==='theme'&&cfg.follow){theme(m.cls,m.colorTheme);}
160
+ });
161
+ if(cfg.size){
162
+ var fit=function(){var W=cfg.size.w,H=cfg.size.h,iw=window.innerWidth||W,ih=window.innerHeight||H;
163
+ var s=Math.min(iw/W,ih/H);if(!(s>0))s=1;
164
+ h.style.setProperty('--canvas-scale',String(s));
165
+ h.style.setProperty('--canvas-x',((iw-W*s)/2)+'px');
166
+ h.style.setProperty('--canvas-y',((ih-H*s)/2)+'px');};
167
+ fit();window.addEventListener('resize',fit);
168
+ }
169
+ var last='';
170
+ function report(msg){var t=String(msg||'the canvas failed');if(t===last)return;last=t;
171
+ try{P.postMessage({v:1,kind:'error',message:t.slice(0,500)},'*');}catch(_){}}
172
+ window.addEventListener('error',function(e){
173
+ if(e&&e.target&&e.target!==window&&e.target.tagName)return;
174
+ report((e&&(e.message||(e.error&&e.error.message)))||'the canvas failed');},true);
175
+ window.addEventListener('unhandledrejection',function(e){
176
+ report((e&&e.reason&&(e.reason.message||e.reason))||'the canvas failed');});
177
+ window.addEventListener('load',function(){
178
+ try{P.postMessage({v:1,kind:'ready',n:nonce},'*');}catch(_){}});
179
+ })();`;
180
+ }
181
+
182
+ /** The ground and fit rules. A fixed canvas draws its body at the design
183
+ * size, scaled and centred; the html ground around it is the letterbox. */
184
+ function layoutCss(size: CanvasSize): string {
185
+ if (size === 'fill') {
186
+ return 'html,body{margin:0;height:100%}body{background:var(--background);color:var(--foreground)}';
187
+ }
188
+ return (
189
+ 'html{margin:0;height:100%;overflow:hidden;' +
190
+ 'background:color-mix(in oklab,var(--foreground) 8%,var(--background))}' +
191
+ `body{position:absolute!important;left:0!important;top:0!important;margin:0!important;` +
192
+ `width:${size.w}px!important;height:${size.h}px!important;overflow:hidden;` +
193
+ 'transform-origin:0 0!important;' +
194
+ 'transform:translate(var(--canvas-x,0px),var(--canvas-y,0px)) scale(var(--canvas-scale,1))!important;' +
195
+ 'background:var(--background);color:var(--foreground)}'
196
+ );
197
+ }
198
+
199
+ /** The canvas source without a leading BOM or doctype (comments before it
200
+ * kept): the frame writes its own doctype first, so the document never
201
+ * parses in quirks mode. A linear scan, not a regex: a nested repeat over
202
+ * comments backtracks exponentially when no doctype follows, and this runs
203
+ * on every frame load (the canvas audit, 2026-10-24). */
204
+ export function stripLeadingDoctype(source: string): string {
205
+ const start = source.charCodeAt(0) === 0xfeff ? 1 : 0;
206
+ let i = start;
207
+ for (;;) {
208
+ while (i < source.length && /\s/.test(source[i]!)) i++;
209
+ if (!source.startsWith('<!--', i)) break;
210
+ const end = source.indexOf('-->', i + 4);
211
+ if (end < 0) return source.slice(start);
212
+ i = end + 3;
213
+ }
214
+ const doctype = /^<!doctype[^>]*>/i.exec(source.slice(i, i + 1024));
215
+ return doctype
216
+ ? source.slice(start, i) + source.slice(i + doctype[0].length)
217
+ : source.slice(start);
218
+ }
219
+
220
+ export function buildCanvasFrameHtml(opts: {
221
+ /** The canvas: the agent's whole HTML document (the stored source). */
222
+ source: string;
223
+ /** Tailwind utilities compiled from the source on save ('' for none). */
224
+ css: string;
225
+ /** The canvas runtime import map JSON ({ imports }). */
226
+ importMapJson: string;
227
+ /** The host page's `<html>` class and data-color-theme at mint time; live
228
+ * changes arrive as theme messages. */
229
+ cls: string;
230
+ colorTheme: string | null;
231
+ /** From the canvas head (parseCanvasHead). */
232
+ size: CanvasSize;
233
+ theme: 'follow' | 'fixed';
234
+ /** `@font-face` rules for Inter and the Appearance library, plus the
235
+ * owner's font vars (`:root{--font-sans:...}`). */
236
+ fontCss: string;
237
+ /** The frame's proof for its parent (canvasFrameNonce); '' for a render
238
+ * with no parent. */
239
+ nonce?: string;
240
+ }): string {
241
+ const follow = opts.theme !== 'fixed';
242
+ // A fixed canvas wears the light baseline: no dark class, no colour theme.
243
+ const cls = follow ? opts.cls : '';
244
+ const colorTheme = follow ? opts.colorTheme : null;
245
+ const prelude = [
246
+ '<meta charset="utf-8" />',
247
+ '<meta name="viewport" content="width=device-width, initial-scale=1" />',
248
+ `<script type="importmap">${opts.importMapJson.replace(/<\//g, '<\\/')}</script>`,
249
+ '<link rel="stylesheet" href="/share-runtime/styles.css" />',
250
+ '<link rel="stylesheet" href="/share-runtime/katex/katex.min.css" />',
251
+ `<style>${styleText(opts.fontCss)}</style>`,
252
+ `<style>${styleText(opts.css)}</style>`,
253
+ `<style>${layoutCss(opts.size)}</style>`,
254
+ `<script>${preludeScript({ cls, colorTheme, followTheme: follow, size: opts.size, nonce: opts.nonce ?? '' })}</script>`,
255
+ ].join('\n');
256
+ return `<!doctype html>\n${prelude}\n${stripLeadingDoctype(opts.source)}`;
257
+ }