@crossworks/share-ui 0.400.13 → 0.400.14

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.400.13",
3
+ "version": "0.400.14",
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": {
@@ -41,14 +41,14 @@
41
41
  "dependencies": {
42
42
  "@dicebear/core": "^10.7.0",
43
43
  "@dicebear/styles": "^10.6.0",
44
- "@mantle/client-types": "npm:@crossworks/client-types@0.400.13",
45
- "@mantle/content-core": "npm:@crossworks/content-core@0.400.13",
46
- "@radix-ui/react-label": "^2.1.16",
47
- "@radix-ui/react-slot": "^1.4.0",
44
+ "@mantle/client-types": "npm:@crossworks/client-types@0.400.14",
45
+ "@mantle/content-core": "npm:@crossworks/content-core@0.400.14",
46
+ "@radix-ui/react-label": "^2.1.17",
47
+ "@radix-ui/react-slot": "^1.5.0",
48
48
  "class-variance-authority": "^0.7.1",
49
49
  "clsx": "^2.1.1",
50
50
  "katex": "0.19.1",
51
- "lucide-react": "^1.52.0",
51
+ "lucide-react": "^1.61.0",
52
52
  "react-markdown": "^10.1.0",
53
53
  "remark-gfm": "^4.0.1",
54
54
  "tailwind-merge": "^3.7.0"
@@ -59,7 +59,7 @@
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/katex": "^0.16.8",
62
- "@types/node": "^26.6.4",
62
+ "@types/node": "^26.6.5",
63
63
  "@types/react": "^19.3.0",
64
64
  "@types/react-dom": "^19.3.0"
65
65
  },
@@ -0,0 +1,193 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { CANVAS_DATA_VALUE_MAX_BYTES } from '@mantle/content-core/canvas-data';
3
+ import { acceptsDataMessage, canvasDataReply, readCanvasDataMessage } from './canvas-data-bridge';
4
+
5
+ const ok = (m: unknown) => {
6
+ const r = readCanvasDataMessage(m);
7
+ if (!r.ok) throw new Error(r.rejection.error);
8
+ return r.req;
9
+ };
10
+ const no = (m: unknown) => {
11
+ const r = readCanvasDataMessage(m);
12
+ if (r.ok) throw new Error(`taken: ${JSON.stringify(r.req)}`);
13
+ return r.rejection;
14
+ };
15
+
16
+ describe('the host reads a frame data message as hostile', () => {
17
+ it('makes a request to its own canvas only: the message names no canvas and no login', () => {
18
+ const req = ok({
19
+ v: 1,
20
+ kind: 'data',
21
+ id: 3,
22
+ op: 'set',
23
+ bucket: 'mine',
24
+ key: 'vote',
25
+ json: '"yes"',
26
+ // What a hostile canvas might add: never read.
27
+ canvas: '00000000-0000-4000-8000-000000000000',
28
+ presentId: 'x',
29
+ login: 'someone',
30
+ url: 'https://evil.example/',
31
+ });
32
+ expect(req).toEqual({
33
+ id: 3,
34
+ op: 'set',
35
+ method: 'PUT',
36
+ path: '/data',
37
+ body: '{"bucket":"mine","key":"vote","value":"yes"}',
38
+ });
39
+ });
40
+
41
+ it('builds each operation', () => {
42
+ expect(ok({ id: 1, op: 'info' }).path).toBe('/data?info=1');
43
+ expect(ok({ id: 1, op: 'get', bucket: 'shared', key: 'a/b' }).path).toBe(
44
+ '/data?bucket=shared&key=a%2Fb',
45
+ );
46
+ expect(ok({ id: 1, op: 'delete', bucket: 'mine', key: 'k' })).toMatchObject({
47
+ method: 'DELETE',
48
+ path: '/data?bucket=mine&key=k',
49
+ });
50
+ expect(ok({ id: 1, op: 'list', bucket: 'mine', everyone: true }).path).toBe(
51
+ '/data?bucket=mine&everyone=1',
52
+ );
53
+ // everyone means nothing for shared.
54
+ expect(ok({ id: 1, op: 'list', bucket: 'shared', everyone: true }).path).toBe(
55
+ '/data?bucket=shared',
56
+ );
57
+ });
58
+
59
+ it('refuses an unknown operation, bucket or key, and a bad id', () => {
60
+ expect(no({ id: 1, op: 'drop', bucket: 'shared', key: 'k' }).error).toMatch(/operation/);
61
+ expect(no({ id: 1, op: '__proto__' }).error).toMatch(/operation/);
62
+ expect(no({ id: 1, op: 'get', bucket: 'everyone', key: 'k' }).error).toMatch(/bucket/);
63
+ expect(no({ id: 1, op: 'get', bucket: 'shared', key: '../x' }).error).toMatch(/key/);
64
+ expect(no({ id: 1, op: 'get', bucket: 'shared', key: 'a&bucket=mine' }).error).toMatch(/key/);
65
+ expect(no({ id: 1, op: 'get', bucket: 'shared', key: { toString: () => 'k' } }).error).toMatch(
66
+ /key/,
67
+ );
68
+ expect(no({ id: 1, op: 'list', bucket: 'mine', everyone: 'yes' }).error).toMatch(/everyone/);
69
+ for (const id of [0, -1, 1.5, '1', null, Number.MAX_VALUE]) {
70
+ expect(no({ id, op: 'info' }).id).toBeNull();
71
+ }
72
+ expect(no(null).id).toBeNull();
73
+ expect(no('get').id).toBeNull();
74
+ expect(no([1]).id).toBeNull();
75
+ });
76
+
77
+ it('takes a value only as JSON text within the cap', () => {
78
+ expect(no({ id: 1, op: 'set', bucket: 'shared', key: 'k', json: { a: 1 } }).error).toMatch(
79
+ /JSON/,
80
+ );
81
+ expect(no({ id: 1, op: 'set', bucket: 'shared', key: 'k', json: '{nope' }).error).toMatch(
82
+ /JSON/,
83
+ );
84
+ expect(no({ id: 1, op: 'set', bucket: 'shared', key: 'k' }).error).toMatch(/JSON/);
85
+ const big = JSON.stringify('x'.repeat(CANVAS_DATA_VALUE_MAX_BYTES));
86
+ expect(no({ id: 1, op: 'set', bucket: 'shared', key: 'k', json: big }).error).toMatch(/KB/);
87
+ // The body carries the canonical text, never the frame's own string.
88
+ expect(ok({ id: 1, op: 'set', bucket: 'shared', key: 'k', json: ' { "a" : 1 } ' }).body).toBe(
89
+ '{"bucket":"shared","key":"k","value":{"a":1}}',
90
+ );
91
+ });
92
+ });
93
+
94
+ describe('the host takes a data message only from the proven document of this load', () => {
95
+ const state = { proven: true, nonce: 'abc123' };
96
+ const msg = { v: 1, kind: 'data', id: 1, op: 'info' };
97
+
98
+ it('takes one with the nonce', () => {
99
+ expect(acceptsDataMessage({ ...msg, n: 'abc123' }, state)).toBe(true);
100
+ });
101
+
102
+ it('ignores the right shape with no nonce, a wrong one, or one of another type', () => {
103
+ for (const n of [
104
+ undefined,
105
+ null,
106
+ '',
107
+ 'abc124',
108
+ 'ABC123',
109
+ ['abc123'],
110
+ { toString: () => 'abc123' },
111
+ ]) {
112
+ expect(acceptsDataMessage({ ...msg, n }, state), String(n)).toBe(false);
113
+ }
114
+ });
115
+
116
+ it('ignores every message before the proof, after a take-down, or with no nonce to hold', () => {
117
+ expect(acceptsDataMessage({ ...msg, n: 'abc123' }, { proven: false, nonce: 'abc123' })).toBe(
118
+ false,
119
+ );
120
+ expect(acceptsDataMessage({ ...msg, n: null }, { proven: true, nonce: null })).toBe(false);
121
+ expect(acceptsDataMessage({ ...msg, n: '' }, { proven: true, nonce: '' })).toBe(false);
122
+ expect(acceptsDataMessage(null, state)).toBe(false);
123
+ });
124
+ });
125
+
126
+ describe('moderation and clear', () => {
127
+ const by = '00000000-0000-4000-8000-000000000001';
128
+ it("removes another viewer's mine entry by its id, and clears with all=1", () => {
129
+ expect(ok({ id: 1, op: 'delete', bucket: 'mine', key: 'v', by })).toMatchObject({
130
+ method: 'DELETE',
131
+ path: `/data?bucket=mine&key=v&by=${by}`,
132
+ });
133
+ expect(ok({ id: 1, op: 'delete', bucket: 'mine', key: 'v', by: null }).path).toBe(
134
+ '/data?bucket=mine&key=v',
135
+ );
136
+ expect(ok({ id: 1, op: 'clear', bucket: 'x', key: '../', by: 'y' })).toEqual({
137
+ id: 1,
138
+ op: 'clear',
139
+ method: 'DELETE',
140
+ path: '/data?all=1',
141
+ });
142
+ });
143
+
144
+ it('refuses a by that is not a login id, or on shared', () => {
145
+ for (const bad of [
146
+ 'me',
147
+ `${by}&all=1`,
148
+ 'ABCDEF00-0000-4000-8000-000000000001',
149
+ 7,
150
+ { id: by },
151
+ ]) {
152
+ expect(no({ id: 1, op: 'delete', bucket: 'mine', key: 'v', by: bad }).error).toMatch(/by/);
153
+ }
154
+ expect(no({ id: 1, op: 'delete', bucket: 'shared', key: 'v', by }).error).toMatch(/by/);
155
+ });
156
+
157
+ it('passes what clear returns', () => {
158
+ expect(canvasDataReply('clear', 200, { removed: 3 })).toEqual({
159
+ ok: true,
160
+ result: { removed: 3 },
161
+ });
162
+ });
163
+ });
164
+
165
+ describe('the frame is told the answer', () => {
166
+ it('passes what each operation returns', () => {
167
+ expect(canvasDataReply('get', 200, { entry: { key: 'k', value: 1 } })).toEqual({
168
+ ok: true,
169
+ result: { key: 'k', value: 1 },
170
+ });
171
+ expect(canvasDataReply('get', 200, { entry: null })).toEqual({ ok: true, result: null });
172
+ expect(canvasDataReply('list', 200, { entries: 'x' })).toEqual({ ok: true, result: [] });
173
+ expect(canvasDataReply('delete', 200, { deleted: true })).toEqual({
174
+ ok: true,
175
+ result: { deleted: true },
176
+ });
177
+ });
178
+
179
+ it('says a refusal in plain words', () => {
180
+ expect(canvasDataReply('set', 403, { error: 'only Write' })).toEqual({
181
+ ok: false,
182
+ error: 'only Write',
183
+ });
184
+ expect(canvasDataReply('get', 404, {})).toEqual({
185
+ ok: false,
186
+ error: 'this canvas is not available',
187
+ });
188
+ expect(canvasDataReply('set', 500, null)).toEqual({
189
+ ok: false,
190
+ error: 'the canvas data store failed (500)',
191
+ });
192
+ });
193
+ });
@@ -0,0 +1,156 @@
1
+ /**
2
+ * The host half of a canvas's `mantle.data` (DWG phase 7a): what CanvasSandbox
3
+ * does with a `{v:1, kind:'data'}` message from its frame. Pure, so every
4
+ * check is tested without a browser (canvas-data-bridge.test.ts).
5
+ *
6
+ * The frame is hostile. Its message is taken only from the document the
7
+ * brain served this load (acceptsDataMessage: the frame's own window, after
8
+ * its proof, carrying the proof's nonce), then checked field by field before
9
+ * any request: a known operation, a known bucket, a key of the contract's
10
+ * format, a value that is JSON text within the cap, a boolean `everyone`, a
11
+ * login id for `by`.
12
+ * Nothing in it names a canvas or a login: the request goes to THIS
13
+ * sandbox's own canvas API (`apiBase`), with the host's own credential
14
+ * (its fetcher), and the brain reads the login from that credential. Any
15
+ * other field the message carries is ignored.
16
+ */
17
+ import {
18
+ isCanvasDataBucket,
19
+ isCanvasDataKey,
20
+ isCanvasDataLoginId,
21
+ isCanvasDataOp,
22
+ readCanvasDataJson,
23
+ type CanvasDataOp,
24
+ } from '@mantle/content-core/canvas-data';
25
+
26
+ /** How many calls of one frame may wait on the brain at once: a canvas that
27
+ * asks more is answered at once with an error (the brain's rate limit is
28
+ * the bound across time). */
29
+ export const CANVAS_DATA_IN_FLIGHT_MAX = 8;
30
+
31
+ /**
32
+ * Whether a `data` message may be forwarded at all: the frame has proved
33
+ * itself this load (`ready` with the nonce), and the message carries that
34
+ * same nonce (`n`). The nonce lives only in the served document's prelude
35
+ * closure, so a page the frame navigated to (the same window, so the same
36
+ * `e.source`) cannot send one, even in the moment before the host sees its
37
+ * load.
38
+ */
39
+ export function acceptsDataMessage(
40
+ m: { n?: unknown } | null | undefined,
41
+ state: { proven: boolean; nonce: string | null },
42
+ ): boolean {
43
+ return (
44
+ !!m &&
45
+ state.proven &&
46
+ typeof state.nonce === 'string' &&
47
+ state.nonce !== '' &&
48
+ m.n === state.nonce
49
+ );
50
+ }
51
+
52
+ /** The request a valid message becomes, relative to the canvas API base. */
53
+ export type CanvasDataRequest = {
54
+ id: number;
55
+ op: CanvasDataOp;
56
+ method: 'GET' | 'PUT' | 'DELETE';
57
+ /** `/data?…`, appended to the sandbox's own `apiBase`. */
58
+ path: string;
59
+ body?: string;
60
+ };
61
+
62
+ /** A message the host answers with an error (when it carries an id it can
63
+ * answer to) or drops. */
64
+ export type CanvasDataRejection = { id: number | null; error: string };
65
+
66
+ function idOf(m: Record<string, unknown>): number | null {
67
+ const id = m.id;
68
+ return typeof id === 'number' && Number.isSafeInteger(id) && id > 0 ? id : null;
69
+ }
70
+
71
+ /** Read a frame's data message: the request to make, or why not. */
72
+ export function readCanvasDataMessage(
73
+ raw: unknown,
74
+ ): { ok: true; req: CanvasDataRequest } | { ok: false; rejection: CanvasDataRejection } {
75
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
76
+ return { ok: false, rejection: { id: null, error: 'not a call' } };
77
+ }
78
+ const m = raw as Record<string, unknown>;
79
+ const id = idOf(m);
80
+ const no = (error: string) => ({ ok: false as const, rejection: { id, error } });
81
+ if (id === null) return no('not a call');
82
+ if (!isCanvasDataOp(m.op)) return no('unknown operation');
83
+ const op = m.op;
84
+ if (op === 'info') return { ok: true, req: { id, op, method: 'GET', path: '/data?info=1' } };
85
+ if (op === 'clear') return { ok: true, req: { id, op, method: 'DELETE', path: '/data?all=1' } };
86
+
87
+ const bucket = m.bucket;
88
+ if (!isCanvasDataBucket(bucket)) return no("bucket must be 'shared' or 'mine'");
89
+ if (op === 'list') {
90
+ if (m.everyone !== undefined && typeof m.everyone !== 'boolean')
91
+ return no('everyone must be true or false');
92
+ const everyone = m.everyone === true && bucket === 'mine';
93
+ const q = new URLSearchParams({ bucket });
94
+ if (everyone) q.set('everyone', '1');
95
+ return { ok: true, req: { id, op, method: 'GET', path: `/data?${q.toString()}` } };
96
+ }
97
+ if (!isCanvasDataKey(m.key)) {
98
+ return no('key must be 1 to 128 letters, digits or _ - . : /, a letter or digit first');
99
+ }
100
+ const key = m.key;
101
+ const q = new URLSearchParams({ bucket, key }).toString();
102
+ if (op === 'get') return { ok: true, req: { id, op, method: 'GET', path: `/data?${q}` } };
103
+ if (op === 'delete') {
104
+ if (m.by === undefined || m.by === null) {
105
+ return { ok: true, req: { id, op, method: 'DELETE', path: `/data?${q}` } };
106
+ }
107
+ if (bucket !== 'mine' || !isCanvasDataLoginId(m.by)) {
108
+ return no("by must be a viewer's id (an entry's by.id), for the 'mine' bucket");
109
+ }
110
+ const qb = new URLSearchParams({ bucket, key, by: m.by }).toString();
111
+ return { ok: true, req: { id, op, method: 'DELETE', path: `/data?${qb}` } };
112
+ }
113
+ // set
114
+ const value = readCanvasDataJson(m.json);
115
+ if (!value.ok) return no(value.error);
116
+ return {
117
+ ok: true,
118
+ req: {
119
+ id,
120
+ op,
121
+ method: 'PUT',
122
+ path: '/data',
123
+ body: `{"bucket":${JSON.stringify(bucket)},"key":${JSON.stringify(key)},"value":${value.text}}`,
124
+ },
125
+ };
126
+ }
127
+
128
+ /** What the frame is told for the brain's answer to `op`. */
129
+ export function canvasDataReply(
130
+ op: CanvasDataOp,
131
+ status: number,
132
+ body: unknown,
133
+ ): { ok: true; result: unknown } | { ok: false; error: string } {
134
+ const b = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};
135
+ if (status >= 200 && status < 300) {
136
+ switch (op) {
137
+ case 'get':
138
+ return { ok: true, result: b.entry ?? null };
139
+ case 'list':
140
+ return { ok: true, result: Array.isArray(b.entries) ? b.entries : [] };
141
+ case 'info':
142
+ return { ok: true, result: b.info ?? null };
143
+ case 'set':
144
+ return { ok: true, result: { updatedAt: b.updatedAt ?? null } };
145
+ case 'delete':
146
+ return { ok: true, result: { deleted: b.deleted === true } };
147
+ case 'clear':
148
+ return { ok: true, result: { removed: typeof b.removed === 'number' ? b.removed : 0 } };
149
+ }
150
+ }
151
+ if (status === 404) return { ok: false, error: 'this canvas is not available' };
152
+ if (status === 429) return { ok: false, error: 'too many calls: wait a moment and try again' };
153
+ if (status === 401) return { ok: false, error: 'signed out: sign in again to save' };
154
+ const said = typeof b.error === 'string' ? b.error.slice(0, 300) : '';
155
+ return { ok: false, error: said || `the canvas data store failed (${status})` };
156
+ }
@@ -1,4 +1,4 @@
1
- import { runInNewContext } from 'node:vm';
1
+ import { runInContext, runInNewContext } from 'node:vm';
2
2
  import { describe, expect, it } from 'vitest';
3
3
  import {
4
4
  buildCanvasEmbedCsp,
@@ -195,6 +195,313 @@ describe('the prelude', () => {
195
195
  });
196
196
  });
197
197
 
198
+ describe('the frame prelude: mantle.data (DWG phase 7a)', () => {
199
+ /** The prelude run in a stand-in window; `nonce` '' is a render. */
200
+ function frame(
201
+ nonce: string,
202
+ canvas?: string,
203
+ o: { source?: string; win?: Record<string, unknown>; globals?: Record<string, unknown> } = {},
204
+ ) {
205
+ const html = buildCanvasFrameHtml({
206
+ source: o.source ?? '<html><body>x</body></html>',
207
+ css: '',
208
+ importMapJson: '{"imports":{}}',
209
+ cls: '',
210
+ colorTheme: null,
211
+ size: 'fill',
212
+ theme: 'follow',
213
+ fontCss: '',
214
+ nonce,
215
+ });
216
+ const prelude = /<script>(\(function\(\)\{[\s\S]*?\}\)\(\);)<\/script>/.exec(html)![1]!;
217
+ const toParent: Record<string, unknown>[] = [];
218
+ const handlers: Record<string, Array<(e: unknown) => void>> = {};
219
+ const options: Record<string, unknown[]> = {};
220
+ const parent = Object.freeze({
221
+ postMessage: (m: Record<string, unknown>) => toParent.push(m),
222
+ });
223
+ const win: Record<string, unknown> = {
224
+ parent,
225
+ addEventListener: (k: string, f: (e: unknown) => void, o?: unknown) => {
226
+ (handlers[k] ??= []).push(f);
227
+ (options[k] ??= []).push(o);
228
+ },
229
+ innerWidth: 800,
230
+ innerHeight: 600,
231
+ ...o.win,
232
+ };
233
+ const el = {
234
+ className: '',
235
+ setAttribute() {},
236
+ removeAttribute() {},
237
+ style: { setProperty() {} },
238
+ };
239
+ const ctx = {
240
+ ...o.globals,
241
+ window: win,
242
+ document: { currentScript: null, documentElement: el },
243
+ Object,
244
+ String,
245
+ Math,
246
+ JSON,
247
+ Promise,
248
+ Error,
249
+ TypeError,
250
+ setTimeout,
251
+ clearTimeout,
252
+ };
253
+ runInNewContext(prelude, ctx);
254
+ // What a canvas runs after the prelude, in the same realm.
255
+ if (canvas) runInContext(canvas, ctx);
256
+ const api = (
257
+ win.mantle as { data?: Record<string, (...a: unknown[]) => Promise<unknown>> } | undefined
258
+ )?.data as Record<string, (...a: unknown[]) => Promise<unknown>>;
259
+ const load = () => {
260
+ for (const f of handlers.load ?? []) f({});
261
+ };
262
+ const reply = (source: unknown, data: unknown) => {
263
+ for (const f of handlers.message ?? []) f({ source, data });
264
+ };
265
+ const pagehide = (persisted: unknown = false) => {
266
+ const e = typeof persisted === 'boolean' ? { persisted } : persisted;
267
+ for (const f of handlers.pagehide ?? []) f(e);
268
+ };
269
+ return { api, toParent, load, reply, parent, pagehide, options, ctx, win, prelude };
270
+ }
271
+
272
+ /** A stand-in for the browser's PageTransitionEvent: `persisted` a
273
+ * prototype getter over an internal slot, as in the browser. */
274
+ function pageTransitionEvent() {
275
+ const slot = new WeakMap<object, boolean>();
276
+ class PageTransitionEvent {
277
+ constructor(persisted: boolean) {
278
+ slot.set(this, persisted);
279
+ }
280
+ }
281
+ Object.defineProperty(PageTransitionEvent.prototype, 'persisted', {
282
+ configurable: true,
283
+ get(this: object) {
284
+ if (!slot.has(this)) throw new TypeError('Illegal invocation');
285
+ return slot.get(this);
286
+ },
287
+ });
288
+ return PageTransitionEvent;
289
+ }
290
+
291
+ it('runs in strict mode', () => {
292
+ expect(frame('n0').prelude.startsWith("(function(){'use strict';")).toBe(true);
293
+ });
294
+
295
+ it('reads persisted through the getter it took first: a canvas that redefines it changes nothing', () => {
296
+ const PageTransitionEvent = pageTransitionEvent();
297
+ const f = frame(
298
+ 'n8',
299
+ `Object.defineProperty(PageTransitionEvent.prototype, 'persisted', { get() { return false; } });`,
300
+ { globals: { PageTransitionEvent } },
301
+ );
302
+ f.load();
303
+ f.pagehide(new PageTransitionEvent(true));
304
+ expect(f.toParent.filter((m) => m.kind === 'leaving')).toEqual([]);
305
+ f.pagehide(new PageTransitionEvent(false));
306
+ expect(f.toParent.filter((m) => m.kind === 'leaving')).toEqual([
307
+ { v: 1, kind: 'leaving', n: 'n8' },
308
+ ]);
309
+ });
310
+
311
+ it('leaves window.mantle alone when the canvas names an element mantle', () => {
312
+ for (const source of [
313
+ '<html><body><div id="mantle">x</div></body></html>',
314
+ "<form name='mantle'></form>",
315
+ '<img name=mantle>',
316
+ '<p\n ID = "mantle">',
317
+ ]) {
318
+ const f = frame('n9', undefined, { source });
319
+ expect(f.win.mantle, source).toBeUndefined();
320
+ }
321
+ // Already taken when the prelude runs: kept as it was.
322
+ const taken = { tagName: 'DIV' };
323
+ const f = frame('n9', undefined, { win: { mantle: taken } });
324
+ expect(f.win.mantle).toBe(taken);
325
+ });
326
+
327
+ it('defines window.mantle when no element is named mantle', () => {
328
+ for (const source of [
329
+ '<html><body><div id="mantle-x" data-id="mantle">x</div></body></html>',
330
+ '<div id="Mantle"></div>',
331
+ '<script>el.id = mantleId</script>',
332
+ ]) {
333
+ const f = frame('n10', undefined, { source });
334
+ expect(Object.keys(f.api ?? {}), source).toContain('set');
335
+ }
336
+ });
337
+
338
+ it('holds every call until ready has gone, and names no canvas and no login', async () => {
339
+ const f = frame('n1');
340
+ const got = f.api.get!('marks');
341
+ const saved = f.api.set!('marks', { a: [1, 2] }, { bucket: 'mine' });
342
+ expect(f.toParent).toEqual([]);
343
+ f.load();
344
+ expect(f.toParent[0]).toEqual({ v: 1, kind: 'ready', n: 'n1' });
345
+ const calls = f.toParent.slice(1);
346
+ expect(calls).toEqual([
347
+ {
348
+ v: 1,
349
+ kind: 'data',
350
+ n: 'n1',
351
+ id: 1,
352
+ op: 'get',
353
+ bucket: 'shared',
354
+ key: 'marks',
355
+ json: undefined,
356
+ everyone: undefined,
357
+ by: undefined,
358
+ },
359
+ {
360
+ v: 1,
361
+ kind: 'data',
362
+ n: 'n1',
363
+ id: 2,
364
+ op: 'set',
365
+ bucket: 'mine',
366
+ key: 'marks',
367
+ json: '{"a":[1,2]}',
368
+ everyone: undefined,
369
+ by: undefined,
370
+ },
371
+ ]);
372
+ for (const c of calls) {
373
+ expect(Object.keys(c).sort()).toEqual([
374
+ 'bucket',
375
+ 'by',
376
+ 'everyone',
377
+ 'id',
378
+ 'json',
379
+ 'key',
380
+ 'kind',
381
+ 'n',
382
+ 'op',
383
+ 'v',
384
+ ]);
385
+ }
386
+ // Only the parent answers: a reply from anyone else is not taken.
387
+ f.reply(
388
+ { postMessage() {} },
389
+ { v: 1, kind: 'data-reply', id: 1, ok: true, result: { value: 'forged' } },
390
+ );
391
+ f.reply(f.parent, {
392
+ v: 1,
393
+ kind: 'data-reply',
394
+ id: 1,
395
+ ok: true,
396
+ result: { key: 'marks', value: 7 },
397
+ });
398
+ f.reply(f.parent, { v: 1, kind: 'data-reply', id: 2, ok: false, error: 'no right' });
399
+ await expect(got).resolves.toBe(7);
400
+ await expect(saved).rejects.toThrow('no right');
401
+ });
402
+
403
+ it('sends a moderation delete and a clear, each with the nonce', async () => {
404
+ const f = frame('n3');
405
+ f.load();
406
+ const by = '00000000-0000-4000-8000-000000000001';
407
+ const del = f.api.delete!('vote', { bucket: 'mine', by });
408
+ const clr = f.api.clear!();
409
+ const calls = f.toParent.filter((m) => m.kind === 'data');
410
+ expect(calls).toMatchObject([
411
+ { n: 'n3', op: 'delete', bucket: 'mine', key: 'vote', by },
412
+ { n: 'n3', op: 'clear' },
413
+ ]);
414
+ f.reply(f.parent, { v: 1, kind: 'data-reply', id: 1, ok: true, result: { deleted: true } });
415
+ f.reply(f.parent, { v: 1, kind: 'data-reply', id: 2, ok: true, result: { removed: 4 } });
416
+ await expect(del).resolves.toBe(true);
417
+ await expect(clr).resolves.toBe(4);
418
+ });
419
+
420
+ it('says leaving, with the nonce, as the document unloads', () => {
421
+ const f = frame('n4');
422
+ f.load();
423
+ f.pagehide();
424
+ expect(f.toParent.at(-1)).toEqual({ v: 1, kind: 'leaving', n: 'n4' });
425
+ // A render (no nonce) says nothing.
426
+ const r = frame('');
427
+ r.load();
428
+ r.pagehide();
429
+ expect(r.toParent.filter((m) => m.kind === 'leaving')).toEqual([]);
430
+ });
431
+
432
+ it('says nothing when the page goes into the back-forward cache (persisted)', () => {
433
+ const f = frame('n5');
434
+ f.load();
435
+ f.pagehide(true);
436
+ expect(f.toParent.filter((m) => m.kind === 'leaving')).toEqual([]);
437
+ f.pagehide(false);
438
+ expect(f.toParent.filter((m) => m.kind === 'leaving')).toEqual([
439
+ { v: 1, kind: 'leaving', n: 'n5' },
440
+ ]);
441
+ });
442
+
443
+ it('takes pagehide in the capture phase, registered before the canvas runs', () => {
444
+ const f = frame('n6');
445
+ expect(f.options.pagehide).toEqual([{ capture: true }]);
446
+ });
447
+
448
+ it('keeps the nonce out of a held call: a canvas that patched push or an index setter reads none', async () => {
449
+ const f = frame(
450
+ 'n7',
451
+ `globalThis.seen = '';
452
+ globalThis.hits = 0;
453
+ const push = Array.prototype.push;
454
+ Array.prototype.push = function (...a) { hits++; seen += JSON.stringify(a); return push.apply(this, a); };
455
+ for (const i of ['0', '1']) {
456
+ Object.defineProperty(Array.prototype, i, {
457
+ configurable: true,
458
+ set(v) {
459
+ hits++;
460
+ seen += JSON.stringify(v);
461
+ Object.defineProperty(this, i, { value: v, writable: true, enumerable: true, configurable: true });
462
+ },
463
+ });
464
+ }`,
465
+ );
466
+ const got = f.api.get!('marks');
467
+ const saved = f.api.set!('marks', 1, { bucket: 'mine' });
468
+ f.load();
469
+ // The canvas saw both held calls go by, and no nonce in either.
470
+ expect(runInContext('hits', f.ctx)).toBeGreaterThan(0);
471
+ const seen = runInContext('seen', f.ctx) as string;
472
+ expect(seen).toContain('marks');
473
+ expect(seen).not.toContain('n7');
474
+ // The parent still gets both calls, each with the nonce.
475
+ expect(f.toParent.filter((m) => m.kind === 'data')).toMatchObject([
476
+ { n: 'n7', id: 1, op: 'get', key: 'marks' },
477
+ { n: 'n7', id: 2, op: 'set', bucket: 'mine', json: '1' },
478
+ ]);
479
+ f.reply(f.parent, { v: 1, kind: 'data-reply', id: 1, ok: true, result: { value: 3 } });
480
+ f.reply(f.parent, { v: 1, kind: 'data-reply', id: 2, ok: true, result: {} });
481
+ await expect(got).resolves.toBe(3);
482
+ await expect(saved).resolves.toBeUndefined();
483
+ });
484
+
485
+ it('refuses a value that is not JSON without sending it', async () => {
486
+ const f = frame('n2');
487
+ f.load();
488
+ await expect(f.api.set!('k', () => 1)).rejects.toThrow('JSON');
489
+ await expect(f.api.set!('k', undefined)).rejects.toThrow('JSON');
490
+ expect(f.toParent.filter((m) => m.kind === 'data')).toEqual([]);
491
+ });
492
+
493
+ it('in a render (no parent proof) reads answer empty and writes refuse, sending nothing', async () => {
494
+ const f = frame('');
495
+ f.load();
496
+ await expect(f.api.get!('k')).resolves.toBeUndefined();
497
+ await expect(f.api.list!()).resolves.toEqual([]);
498
+ await expect(f.api.info!()).resolves.toMatchObject({ canWriteShared: false, readOnly: true });
499
+ await expect(f.api.set!('k', 1)).rejects.toThrow('picture');
500
+ await expect(f.api.clear!()).rejects.toThrow('picture');
501
+ expect(f.toParent.filter((m) => m.kind === 'data')).toEqual([]);
502
+ });
503
+ });
504
+
198
505
  describe('buildCanvasEmbedCsp', () => {
199
506
  it('requires no network of whatever loads in the frame, and names only what an embedder may', () => {
200
507
  const csp = buildCanvasEmbedCsp('https://brain.example');
@@ -19,6 +19,7 @@
19
19
  * fetch, no form posts, no popups, no top navigation.
20
20
  */
21
21
  import type { CanvasSize } from '@mantle/content-core/canvas';
22
+ import { CANVAS_DATA_CALL_TIMEOUT_MS } from '@mantle/content-core/canvas-data';
22
23
 
23
24
  /**
24
25
  * The canvas frame CSP, sent as a HEADER (section 5.2). Every source names
@@ -124,6 +125,28 @@ function styleText(css: string): string {
124
125
  * or rejection as `{v:1, kind:'error', message}` (deduplicated), so the
125
126
  * host can tell a broken canvas from a slow one. The parent checks
126
127
  * `e.source` and accepts nothing else.
128
+ * - Data (DWG phase 7a): `window.mantle.data` (get, set, delete, list,
129
+ * info, clear), each a promise; not on a canvas that names an element
130
+ * mantle (namesMantle), whose window.mantle stays that element. A call is `{v:1, kind:'data', n, id, op,
131
+ * bucket, key, json, everyone, by}` to the parent, held until `ready` has
132
+ * gone (the parent takes none before the proof), and answered by
133
+ * `{v:1, kind:'data-reply', id, ok, result | error}` from the parent only.
134
+ * `n` is the nonce again, from this closure: the parent drops a data
135
+ * message without it, so a page the frame navigated to (the same window)
136
+ * sends nothing it takes. A call waiting for `ready` is held without it;
137
+ * `n` goes on only in the object handed straight to the parent's
138
+ * postMessage (captured first), so a canvas that patched a built-in
139
+ * (Array.prototype.push, a setter on a prototype) never sees it. The
140
+ * message names no canvas and no login: the
141
+ * parent binds both, and checks every field (canvas-sandbox.tsx). A
142
+ * canvas that never calls it sends nothing. With no parent (a render: no
143
+ * nonce) reads answer empty and writes refuse, at once.
144
+ * - Leaving: `{v:1, kind:'leaving', n}` as the document unloads (pagehide,
145
+ * taken in the capture phase, registered before any canvas code runs),
146
+ * so the parent takes the frame down before a navigated-to page runs.
147
+ * Not when the page goes into the back-forward cache (`persisted`): it
148
+ * is kept, not left, and a canvas that never used the store keeps its
149
+ * frame when the viewer goes Back.
127
150
  */
128
151
  function preludeScript(opts: {
129
152
  cls: string;
@@ -131,6 +154,8 @@ function preludeScript(opts: {
131
154
  followTheme: boolean;
132
155
  size: CanvasSize;
133
156
  nonce: string;
157
+ /** The canvas names an element mantle (namesMantle): window.mantle stays its. */
158
+ named: boolean;
134
159
  }): string {
135
160
  const cfg = scriptJson({
136
161
  cls: opts.cls,
@@ -138,6 +163,7 @@ function preludeScript(opts: {
138
163
  follow: opts.followTheme,
139
164
  size: opts.size === 'fill' ? null : opts.size,
140
165
  n: opts.nonce,
166
+ named: opts.named,
141
167
  });
142
168
  // The script takes itself out of the document as it runs: the nonce lives
143
169
  // on only in this closure, out of the canvas's reach (it runs later, in the
@@ -145,19 +171,53 @@ function preludeScript(opts: {
145
171
  // is read once, first: `window.parent` is replaceable, and a canvas that
146
172
  // set it to an object of its own would be handed the nonce at load. The
147
173
  // real parent is another origin's window, whose postMessage a canvas
148
- // cannot change.
149
- return `(function(){
174
+ // cannot change. The bfcache test reads `persisted` through the getter
175
+ // taken here, not off the event: a canvas could redefine it later.
176
+ return `(function(){'use strict';
150
177
  var P=window.parent;
178
+ var persisted=(function(){try{var d=Object.getOwnPropertyDescriptor(PageTransitionEvent.prototype,'persisted');
179
+ return d&&typeof d.get==='function'?Function.prototype.call.bind(d.get):null;}catch(_){return null;}})();
180
+ function kept(e){if(!e)return false;if(!persisted)return !!e.persisted;try{return !!persisted(e);}catch(_){return false;}}
151
181
  var me=document.currentScript;if(me&&me.parentNode){me.parentNode.removeChild(me);}
152
182
  var cfg=${cfg};var h=document.documentElement;var nonce=cfg.n;cfg.n='';
153
183
  ['RTCPeerConnection','webkitRTCPeerConnection','RTCDataChannel','RTCIceCandidate','RTCSessionDescription'].forEach(function(n){
154
184
  try{Object.defineProperty(window,n,{value:undefined,writable:false,configurable:false});}catch(_){}});
155
185
  function theme(cls,ct){h.className=cls||'';if(ct){h.setAttribute('data-color-theme',ct);}else{h.removeAttribute('data-color-theme');}}
156
186
  theme(cfg.cls,cfg.ct);
187
+ var waits=Object.create(null),seq=0,up=false,queue=[],qn=0,noHost=!nonce;
188
+ window.addEventListener('pagehide',function(e){
189
+ if(nonce&&!kept(e)){try{P.postMessage({v:1,kind:'leaving',n:nonce},'*');}catch(_){}}},{capture:true});
157
190
  window.addEventListener('message',function(e){
158
191
  if(e.source!==P)return;var m=e.data;if(!m||m.v!==1)return;
159
192
  if(m.kind==='theme'&&cfg.follow){theme(m.cls,m.colorTheme);}
193
+ else if(m.kind==='data-reply'){var w=waits[m.id];if(!w)return;delete waits[m.id];clearTimeout(w.t);
194
+ if(m.ok===true){w.ok(m.result);}else{w.no(new Error(typeof m.error==='string'?m.error.slice(0,300):'the canvas data store refused'));}}
160
195
  });
196
+ function send(r){try{P.postMessage({v:1,kind:'data',n:nonce,id:r.id,op:r.op,bucket:r.bucket,key:r.key,json:r.json,everyone:r.everyone,by:r.by},'*');}
197
+ catch(_){var w=waits[r.id];if(w){delete waits[r.id];clearTimeout(w.t);w.no(new Error('the canvas data store is not available'));}}}
198
+ function call(op,a){return new Promise(function(ok,no){
199
+ if(noHost){
200
+ if(op==='get'){ok(null);}else if(op==='list'){ok([]);}
201
+ else if(op==='info'){ok({canWriteShared:false,readsEveryone:false,me:null,readOnly:true});}
202
+ else{no(new Error('nothing is saved here: this is a picture of the canvas'));}
203
+ return;}
204
+ var id=++seq;var t=setTimeout(function(){if(waits[id]){delete waits[id];no(new Error('the canvas data store did not answer'));}},${CANVAS_DATA_CALL_TIMEOUT_MS + 5_000});
205
+ waits[id]={ok:ok,no:no,t:t};
206
+ var r={id:id,op:op,bucket:a.bucket,key:a.key,json:a.json,everyone:a.everyone,by:a.by};
207
+ if(up){send(r);}else{queue[qn++]=r;}
208
+ });}
209
+ function bk(o){return o&&typeof o==='object'&&o.bucket!==undefined?o.bucket:'shared';}
210
+ var data={
211
+ get:function(k,o){return call('get',{bucket:bk(o),key:k}).then(function(r){return r&&typeof r==='object'?r.value:undefined;});},
212
+ set:function(k,v,o){var j;try{j=JSON.stringify(v);}catch(err){return Promise.reject(err);}
213
+ if(j===undefined){return Promise.reject(new TypeError('the value must be JSON'));}
214
+ return call('set',{bucket:bk(o),key:k,json:j}).then(function(){return undefined;});},
215
+ delete:function(k,o){return call('delete',{bucket:bk(o),key:k,by:o&&typeof o==='object'?o.by:undefined}).then(function(r){return !!(r&&r.deleted);});},
216
+ list:function(o){return call('list',{bucket:bk(o),everyone:!!(o&&typeof o==='object'&&o.everyone)});},
217
+ info:function(){return call('info',{});},
218
+ clear:function(){return call('clear',{}).then(function(r){return r&&typeof r.removed==='number'?r.removed:0;});}
219
+ };
220
+ if(!cfg.named&&!('mantle' in window)){try{window.mantle=Object.freeze({data:Object.freeze(data)});}catch(_){}}
161
221
  if(cfg.size){
162
222
  var fit=function(){var W=cfg.size.w,H=cfg.size.h,iw=window.innerWidth||W,ih=window.innerHeight||H;
163
223
  var s=Math.min(iw/W,ih/H);if(!(s>0))s=1;
@@ -175,10 +235,23 @@ function preludeScript(opts: {
175
235
  window.addEventListener('unhandledrejection',function(e){
176
236
  report((e&&e.reason&&(e.reason.message||e.reason))||'the canvas failed');});
177
237
  window.addEventListener('load',function(){
178
- try{P.postMessage({v:1,kind:'ready',n:nonce},'*');}catch(_){}});
238
+ try{P.postMessage({v:1,kind:'ready',n:nonce},'*');}catch(_){}
239
+ up=true;var q=queue,k=qn;queue=null;qn=0;for(var i=0;i<k;i++){send(q[i]);}});
179
240
  })();`;
180
241
  }
181
242
 
243
+ /** Whether the canvas names an element mantle (id="mantle", or name="mantle"
244
+ * on a form, img, embed, object or iframe): the browser hands that element
245
+ * out as window.mantle, and the prelude's own window.mantle would hide it.
246
+ * The prelude runs before the canvas body is parsed, so it reads this from
247
+ * the source; a false match only costs that canvas mantle.data. Linear: no
248
+ * nested repeat. */
249
+ export function namesMantle(source: string): boolean {
250
+ return /(?:^|[\s"'/])(?:[iI][dD]|[nN][aA][mM][eE])\s*=\s*(?:"mantle"|'mantle'|mantle(?=[\s/>]|$))/.test(
251
+ source,
252
+ );
253
+ }
254
+
182
255
  /** The ground and fit rules. A fixed canvas draws its body at the design
183
256
  * size, scaled and centred; the html ground around it is the letterbox. */
184
257
  function layoutCss(size: CanvasSize): string {
@@ -242,6 +315,7 @@ export function buildCanvasFrameHtml(opts: {
242
315
  // A fixed canvas wears the light baseline: no dark class, no colour theme.
243
316
  const cls = follow ? opts.cls : '';
244
317
  const colorTheme = follow ? opts.colorTheme : null;
318
+ const source = stripLeadingDoctype(opts.source);
245
319
  const prelude = [
246
320
  '<meta charset="utf-8" />',
247
321
  '<meta name="viewport" content="width=device-width, initial-scale=1" />',
@@ -251,7 +325,7 @@ export function buildCanvasFrameHtml(opts: {
251
325
  `<style>${styleText(opts.fontCss)}</style>`,
252
326
  `<style>${styleText(opts.css)}</style>`,
253
327
  `<style>${layoutCss(opts.size)}</style>`,
254
- `<script>${preludeScript({ cls, colorTheme, followTheme: follow, size: opts.size, nonce: opts.nonce ?? '' })}</script>`,
328
+ `<script>${preludeScript({ cls, colorTheme, followTheme: follow, size: opts.size, nonce: opts.nonce ?? '', named: namesMantle(source) })}</script>`,
255
329
  ].join('\n');
256
- return `<!doctype html>\n${prelude}\n${stripLeadingDoctype(opts.source)}`;
330
+ return `<!doctype html>\n${prelude}\n${source}`;
257
331
  }
@@ -5,8 +5,22 @@
5
5
  * canvas-files.md section 5.2). Like AppSandbox (./app-sandbox.tsx), the
6
6
  * iframe NAVIGATES to a brain-rendered frame document, after this parent
7
7
  * mints a seconds-lived ticket for it (the sandboxed navigation can carry no
8
- * credential). Unlike an app there is no bridge: the frame may post `ready`
9
- * and `error`, and this parent posts `theme`. Nothing else crosses.
8
+ * credential). Unlike an app there is no tool or database bridge: the frame
9
+ * may post `ready`, `error` and `data`, and this parent posts `theme` and
10
+ * `data-reply`. Nothing else crosses.
11
+ *
12
+ * Data (DWG phase 7a): a canvas's `mantle.data` calls arrive as `data`
13
+ * messages. This parent takes them only from its own frame (`e.source`),
14
+ * only once the frame proved itself (`ready` with the nonce), and only when
15
+ * the message carries that nonce again (`n`): a page the frame navigated to
16
+ * is the same window but never knows it. It checks every field
17
+ * (./canvas-data-bridge.ts) and forwards each to THIS canvas's API
18
+ * (`apiBase` + `/data`) with its own fetcher: the canvas names no canvas and
19
+ * no login, and never holds a credential. At most CANVAS_DATA_IN_FLIGHT_MAX
20
+ * wait at once, each at most 30 s. A canvas that never calls it costs no
21
+ * request. The served document says `leaving` (with the nonce) as it
22
+ * unloads, so a navigation takes the frame down before the next page runs
23
+ * anything, not at its load.
10
24
  *
11
25
  * The iframe is `sandbox="allow-scripts"` only: an opaque origin, no
12
26
  * cookies, no storage, no forms, no popups, no top navigation. The frame's
@@ -26,6 +40,13 @@
26
40
  */
27
41
  import { useEffect, useRef, useState, type ReactNode, type Ref } from 'react';
28
42
  import { buildCanvasEmbedCsp } from './canvas-frame-html';
43
+ import {
44
+ CANVAS_DATA_IN_FLIGHT_MAX,
45
+ acceptsDataMessage,
46
+ canvasDataReply,
47
+ readCanvasDataMessage,
48
+ } from './canvas-data-bridge';
49
+ import { CANVAS_DATA_CALL_TIMEOUT_MS } from '@mantle/content-core/canvas-data';
29
50
 
30
51
  type Status = 'loading' | 'ready' | 'error' | 'missing' | 'left';
31
52
 
@@ -87,6 +108,17 @@ export function CanvasSandbox({
87
108
  // The latest callbacks, read by the effects without re-running them.
88
109
  const handlers = useRef({ onReady, onDown, onError, fetcher });
89
110
  handlers.current = { onReady, onDown, onError, fetcher };
111
+ // The frame load each data call belongs to: a reply to an earlier load
112
+ // (a reload, Replay, a take-down) is dropped, never sent to the new one,
113
+ // and the in-flight count starts again with each load.
114
+ const frameLoad = useRef(0);
115
+ const dataInFlight = useRef(0);
116
+ const nextLoad = () => {
117
+ frameLoad.current += 1;
118
+ dataInFlight.current = 0;
119
+ };
120
+ const apiBaseRef = useRef(apiBase);
121
+ apiBaseRef.current = apiBase;
90
122
 
91
123
  // Mint a ticket and point the frame at the document it opens.
92
124
  useEffect(() => {
@@ -94,6 +126,7 @@ export function CanvasSandbox({
94
126
  setStatus('loading');
95
127
  setFailure(null);
96
128
  setSrc(null);
129
+ nextLoad();
97
130
  handlers.current.onDown?.();
98
131
  void (async () => {
99
132
  try {
@@ -129,6 +162,10 @@ export function CanvasSandbox({
129
162
  const takeDown = (why: string) => {
130
163
  if (proofWait.current) clearTimeout(proofWait.current);
131
164
  proofWait.current = null;
165
+ proven.current = false;
166
+ nonce.current = null;
167
+ frameLoad.current += 1;
168
+ dataInFlight.current = 0;
132
169
  setSrc(null);
133
170
  setStatus('left');
134
171
  handlers.current.onDown?.();
@@ -146,7 +183,7 @@ export function CanvasSandbox({
146
183
  return () => clearTimeout(t);
147
184
  }, [src]);
148
185
 
149
- // The frame's two messages, from this frame only.
186
+ // The frame's messages, from this frame only.
150
187
  useEffect(() => {
151
188
  function onMessage(e: MessageEvent) {
152
189
  const frame = iframeRef.current;
@@ -165,6 +202,52 @@ export function CanvasSandbox({
165
202
  const text = typeof m.message === 'string' ? m.message.slice(0, 500) : 'the canvas failed';
166
203
  setFailure(text);
167
204
  handlers.current.onError?.(text);
205
+ } else if (m.kind === 'leaving') {
206
+ // The served document unloads: whatever loads next is not the
207
+ // canvas. Taken down now, before that page runs anything.
208
+ if (!acceptsDataMessage(m, { proven: proven.current, nonce: nonce.current })) return;
209
+ takeDown('the canvas tried to open another page');
210
+ } else if (m.kind === 'data') {
211
+ // Only the proven document, and only with its nonce: the frame's
212
+ // window may hold a page the canvas navigated to.
213
+ if (!acceptsDataMessage(m, { proven: proven.current, nonce: nonce.current })) return;
214
+ void forwardData(frame, m);
215
+ }
216
+ }
217
+
218
+ /** One `mantle.data` call, checked, forwarded and answered. */
219
+ async function forwardData(frame: HTMLIFrameElement, raw: unknown) {
220
+ const load = frameLoad.current;
221
+ const answer = (id: number | null, reply: Record<string, unknown>) => {
222
+ if (id === null || load !== frameLoad.current || !proven.current) return;
223
+ frame.contentWindow?.postMessage({ v: 1, kind: 'data-reply', id, ...reply }, '*');
224
+ };
225
+ const read = readCanvasDataMessage(raw);
226
+ if (!read.ok) {
227
+ answer(read.rejection.id, { ok: false, error: read.rejection.error });
228
+ return;
229
+ }
230
+ const { req } = read;
231
+ if (dataInFlight.current >= CANVAS_DATA_IN_FLIGHT_MAX) {
232
+ answer(req.id, { ok: false, error: 'too many calls at once: wait for the ones sent' });
233
+ return;
234
+ }
235
+ dataInFlight.current += 1;
236
+ try {
237
+ const res = await handlers.current.fetcher(`${apiBaseRef.current}${req.path}`, {
238
+ method: req.method,
239
+ signal: AbortSignal.timeout(CANVAS_DATA_CALL_TIMEOUT_MS),
240
+ ...(req.body !== undefined
241
+ ? { headers: { 'content-type': 'application/json' }, body: req.body }
242
+ : {}),
243
+ });
244
+ const body: unknown = await res.json().catch(() => null);
245
+ answer(req.id, canvasDataReply(req.op, res.status, body));
246
+ } catch {
247
+ answer(req.id, { ok: false, error: 'the canvas data store could not be reached' });
248
+ } finally {
249
+ // A call of an earlier load is not counted in this one's.
250
+ if (load === frameLoad.current) dataInFlight.current -= 1;
168
251
  }
169
252
  }
170
253
  window.addEventListener('message', onMessage);
package/src/nav-items.ts CHANGED
@@ -104,8 +104,8 @@ export const NAV_GROUPS: NavGroup[] = [
104
104
  label: 'Workspace',
105
105
  items: [
106
106
  // Every login's landing page: the current workspace's home app or the
107
- // Built-in home (task d78e7bde). The brain health Dashboard is System.
108
- { name: 'Home', href: '/', icon: LayoutDashboard, exact: true },
107
+ // built-in Desk (task d78e7bde). The brain health Dashboard is System.
108
+ { name: 'Desk', href: '/', icon: LayoutDashboard, exact: true },
109
109
  { name: 'Journal', href: '/journal', icon: NotebookPen },
110
110
  { name: 'Email', href: '/inbox', icon: Inbox },
111
111
  { name: 'Files', href: '/files', icon: FolderTree },