@1agh/maude 1.7.1 → 1.9.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.
Files changed (108) hide show
  1. package/apps/studio/acp/bridge.ts +15 -2
  2. package/apps/studio/acp/login-state.ts +1 -0
  3. package/apps/studio/acp/probe.ts +52 -1
  4. package/apps/studio/api.ts +431 -39
  5. package/apps/studio/asset-upload.ts +174 -0
  6. package/apps/studio/assets-s3.ts +37 -2
  7. package/apps/studio/bin/_curl-local.mjs +7 -0
  8. package/apps/studio/bin/_pdf-playwright.mjs +22 -1
  9. package/apps/studio/bin/_png-playwright.mjs +20 -1
  10. package/apps/studio/bin/_region.mjs +92 -0
  11. package/apps/studio/bin/annotate.mjs +16 -7
  12. package/apps/studio/bin/read-annotations.mjs +62 -4
  13. package/apps/studio/canvas-build.ts +59 -4
  14. package/apps/studio/canvas-lib.tsx +48 -1
  15. package/apps/studio/canvas-shell.tsx +28 -4
  16. package/apps/studio/client/app.jsx +441 -15903
  17. package/apps/studio/client/canvas-url.js +9 -0
  18. package/apps/studio/client/dialogs/asset-picker.jsx +331 -0
  19. package/apps/studio/client/dialogs/command-palette.jsx +112 -0
  20. package/apps/studio/client/dialogs/export-dialog.jsx +782 -0
  21. package/apps/studio/client/dialogs/help-modal.jsx +324 -0
  22. package/apps/studio/client/dialogs/shortcuts-overlay.jsx +144 -0
  23. package/apps/studio/client/embed-view.jsx +284 -0
  24. package/apps/studio/client/embed.js +101 -0
  25. package/apps/studio/client/export-center.jsx +2 -0
  26. package/apps/studio/client/github.js +36 -3
  27. package/apps/studio/client/hooks/use-canvas-bridge.jsx +2150 -0
  28. package/apps/studio/client/hooks/use-git-actions.jsx +236 -0
  29. package/apps/studio/client/hooks/use-keyboard-shortcuts.jsx +297 -0
  30. package/apps/studio/client/hooks/use-palette-and-panels.jsx +474 -0
  31. package/apps/studio/client/hooks/use-photo-and-timeline.jsx +901 -0
  32. package/apps/studio/client/hooks/use-project-data.jsx +90 -0
  33. package/apps/studio/client/hooks/use-shell-core.jsx +1212 -0
  34. package/apps/studio/client/hooks/use-tabs.jsx +723 -0
  35. package/apps/studio/client/hooks/use-web-socket.jsx +13 -0
  36. package/apps/studio/client/inspector/artboard-knobs.jsx +456 -0
  37. package/apps/studio/client/inspector/color-picker.jsx +196 -0
  38. package/apps/studio/client/inspector/color.js +92 -0
  39. package/apps/studio/client/inspector/css-knobs.jsx +1720 -0
  40. package/apps/studio/client/inspector/css-vocab.jsx +131 -0
  41. package/apps/studio/client/inspector/ds-tokens.js +90 -0
  42. package/apps/studio/client/inspector/grid-tracks-editor.jsx +97 -0
  43. package/apps/studio/client/inspector/inspect-computed.jsx +68 -0
  44. package/apps/studio/client/inspector/inspector-panel.jsx +769 -0
  45. package/apps/studio/client/inspector/layers.jsx +322 -0
  46. package/apps/studio/client/inspector/selection.js +65 -0
  47. package/apps/studio/client/inspector/token-popover.jsx +301 -0
  48. package/apps/studio/client/menus/menubar.jsx +856 -0
  49. package/apps/studio/client/report-bug.jsx +8 -2
  50. package/apps/studio/client/selection-scope.js +40 -0
  51. package/apps/studio/client/shell/banners.jsx +272 -0
  52. package/apps/studio/client/shell/collapsed-rail.jsx +23 -0
  53. package/apps/studio/client/shell/comments-panel.jsx +177 -0
  54. package/apps/studio/client/shell/constants.js +60 -0
  55. package/apps/studio/client/shell/dock.jsx +131 -0
  56. package/apps/studio/client/shell/icons.jsx +370 -0
  57. package/apps/studio/client/shell/status-bar.jsx +215 -0
  58. package/apps/studio/client/shell/util.js +332 -0
  59. package/apps/studio/client/shell/viewport.jsx +254 -0
  60. package/apps/studio/client/system/system-view.jsx +255 -0
  61. package/apps/studio/client/tree/tree.jsx +1243 -0
  62. package/apps/studio/comments-overlay.tsx +6 -4
  63. package/apps/studio/config.schema.json +5 -0
  64. package/apps/studio/context.ts +20 -0
  65. package/apps/studio/dist/client.bundle.js +2728 -2728
  66. package/apps/studio/dist/comment-mount.js +2 -2
  67. package/apps/studio/embed-origins.ts +52 -0
  68. package/apps/studio/export-dialog.tsx +55 -3
  69. package/apps/studio/exporters/_browser-bundles.ts +21 -2
  70. package/apps/studio/exporters/format-scopes.ts +11 -3
  71. package/apps/studio/exporters/index.ts +17 -2
  72. package/apps/studio/exporters/jobs.ts +91 -23
  73. package/apps/studio/exporters/pdf.ts +10 -2
  74. package/apps/studio/exporters/png.ts +10 -2
  75. package/apps/studio/exporters/scope.ts +89 -15
  76. package/apps/studio/format.ts +296 -0
  77. package/apps/studio/generation/runtime-probe.ts +1 -1
  78. package/apps/studio/git/service.ts +1 -0
  79. package/apps/studio/http.ts +399 -36
  80. package/apps/studio/input-router.tsx +7 -1
  81. package/apps/studio/path-containment.ts +72 -0
  82. package/apps/studio/paths.ts +14 -1
  83. package/apps/studio/read-only-mode.ts +53 -0
  84. package/apps/studio/server.ts +123 -25
  85. package/apps/studio/sync/accepted-link.ts +6 -0
  86. package/apps/studio/sync/agent.ts +9 -1
  87. package/apps/studio/sync/cold-start-apply.ts +29 -4
  88. package/apps/studio/sync/cold-start.ts +78 -0
  89. package/apps/studio/sync/file-plane.ts +61 -1
  90. package/apps/studio/sync/format-sync.ts +160 -0
  91. package/apps/studio/sync/index.ts +208 -23
  92. package/apps/studio/sync/journal-client.ts +25 -5
  93. package/apps/studio/sync/migrate-seed.ts +8 -1
  94. package/apps/studio/sync/park.ts +39 -0
  95. package/apps/studio/sync/presentation.ts +9 -3
  96. package/apps/studio/sync/status.ts +2 -0
  97. package/apps/studio/sync/transaction-client.ts +130 -13
  98. package/apps/studio/sync/writer-registry.ts +5 -0
  99. package/apps/studio/ui-prefs.ts +95 -10
  100. package/apps/studio/use-canvas-media-drop.tsx +8 -28
  101. package/apps/studio/whats-new.json +36 -0
  102. package/apps/studio/ws.ts +19 -4
  103. package/cli/bin/claude-design-server.mjs +0 -0
  104. package/cli/commands/design.mjs +9 -2
  105. package/cli/commands/hub-workspace.mjs +25 -0
  106. package/cli/lib/workspace-plan.mjs +51 -0
  107. package/package.json +11 -9
  108. package/plugins/design/templates/_shell.html +58 -0
@@ -31,7 +31,7 @@ import {
31
31
  readChatMessages,
32
32
  writeChatMeta,
33
33
  } from './acp/transcript.ts';
34
- import { type Api, ASSET_MAX_BYTES, ASSET_MAX_VIDEO_BYTES } from './api.ts';
34
+ import { type Api, ASSET_CHUNK_BYTES, ASSET_MAX_BYTES, ASSET_MAX_VIDEO_BYTES } from './api.ts';
35
35
  import { ImportAssetError, importSvg, SVG_MAX_BYTES } from './bin/_import-asset.mjs';
36
36
  import { ImportBrandError, importBrand } from './bin/_import-brand.mjs';
37
37
  import { buildCanvasModule } from './canvas-build.ts';
@@ -45,6 +45,7 @@ import type { Context } from './context.ts';
45
45
  import { reloadConfig } from './context.ts';
46
46
  import { buildDebugBundle } from './debug-bundle.ts';
47
47
  import { probeSetupReadiness } from './design-setup-readiness.ts';
48
+ import { frameAncestors } from './embed-origins.ts';
48
49
  import { isScopeValidForFormat, scopeRefusalMessage } from './exporters/format-scopes.ts';
49
50
  import { type Format, isFormat, isScope, type Scope } from './exporters/index.ts';
50
51
  import { type ExportJobQueue, ExportQueueFullError } from './exporters/jobs.ts';
@@ -52,6 +53,14 @@ import type { ActiveJsonShape } from './exporters/scope.ts';
52
53
  import { createFigmaEndpoints } from './figma/endpoints.ts';
53
54
  import { generatedClipAnalysis } from './footage/schema.ts';
54
55
  import { createFootageStore, FOOTAGE_MAX_BYTES } from './footage-store.ts';
56
+ import {
57
+ canvasFormatLine,
58
+ formatGate,
59
+ formatGateAllowsWrite,
60
+ formatRefusalResponse,
61
+ projectFormat,
62
+ STAGED_FORMAT_GATE_OPTS,
63
+ } from './format.ts';
55
64
  import {
56
65
  type AudioMatch,
57
66
  type Candidate,
@@ -111,6 +120,7 @@ import type { InspectRegistry } from './inspect.ts';
111
120
  import { canvasSlug, writeLocator } from './locator.ts';
112
121
  import { prepareManagedProject } from './managed-projects.ts';
113
122
  import { materializeMissing } from './materialize-client.ts';
123
+ import { isUnderOrEqual, resolveUrlPathUnder } from './path-containment.ts';
114
124
  import { BIN_DIR, DEV_SERVER_ROOT, MEDIA_DIR, STICKERS_DIR } from './paths.ts';
115
125
  import { createPhotoStore, PHOTO_EDIT_MAX_BYTES } from './photo-store.ts';
116
126
  import { probeReadiness } from './readiness.ts';
@@ -232,7 +242,35 @@ export function rootIdentity(root: string): string {
232
242
  return createHash('sha256').update(resolved, 'utf8').digest('hex').slice(0, 12);
233
243
  }
234
244
 
235
- export function cspForCanvasShell(html: string, mainOrigin?: string): string {
245
+ /**
246
+ * DDR-247 — the studio page's CSP. Always `frame-ancestors`; in the `?embed=1`
247
+ * view also `frame-src 'self' <canvas origin>`: the embed frames exactly one
248
+ * canvas, and a hostile canvas must not be able to navigate its own frame to a
249
+ * foreign origin (a look-alike sign-in page) inside someone else's app.
250
+ */
251
+ export function studioPageCsp(
252
+ mainOrigin: string | undefined,
253
+ embedOrigins: readonly string[],
254
+ { embed = false, canvasOrigin }: { embed?: boolean; canvasOrigin?: string } = {}
255
+ ): string {
256
+ const directives = [`frame-ancestors ${frameAncestors(mainOrigin, embedOrigins)}`];
257
+ if (embed) {
258
+ let canvas = '';
259
+ try {
260
+ canvas = canvasOrigin ? new URL(canvasOrigin).origin : '';
261
+ } catch {
262
+ /* unparseable — 'self' alone, the canvas then fails closed */
263
+ }
264
+ directives.push(`frame-src ${["'self'", canvas].filter(Boolean).join(' ')}`);
265
+ }
266
+ return directives.join('; ');
267
+ }
268
+
269
+ export function cspForCanvasShell(
270
+ html: string,
271
+ mainOrigin?: string,
272
+ embedOrigins: readonly string[] = []
273
+ ): string {
236
274
  const hashes: string[] = [];
237
275
  // Match inline <script> blocks only (no src=). `[^>]*` excludes any with src.
238
276
  const re = /<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi;
@@ -262,13 +300,25 @@ export function cspForCanvasShell(html: string, mainOrigin?: string): string {
262
300
  "form-action 'none'",
263
301
  "webrtc 'block'",
264
302
  ];
265
- if (mainOrigin) directives.push(`frame-ancestors 'self' ${mainOrigin}`);
303
+ // DDR-247 — an embedder of the studio page is an ANCESTOR of this frame too,
304
+ // and frame-ancestors checks every ancestor, so it is listed here as well.
305
+ if (mainOrigin) directives.push(`frame-ancestors ${frameAncestors(mainOrigin, embedOrigins)}`);
266
306
  return directives.join('; ');
267
307
  }
268
308
 
269
309
  /**
270
- * CSP for the EXPORT/CAPTURE render (DDR-148 security, attacker F1). The export
271
- * renders the (untrusted, DDR-054) canvas on the MAIN origin — where the normal
310
+ * CSP for a main-origin CAPTURE render (DDR-148 security, attacker F1).
311
+ *
312
+ * V2-2.8 S9: while the origin split is on, captures no longer render on the
313
+ * main origin at all — the main origin 307s them to the read-only capture
314
+ * origin, which serves the strict canvas CSP (`cspForCanvasShell`, DDR-232).
315
+ * This policy now applies only where a capture still renders on the main
316
+ * origin: with the split OFF (`MAUDE_CANVAS_ORIGIN_SPLIT=0`). (Maude's own
317
+ * local `_draw/` / `_photo/` harnesses stay on the main origin too, but only
318
+ * as bare `?canvas=` requests — one carrying `hide-chrome` is redirected.)
319
+ *
320
+ * Original rationale: the export rendered the (untrusted, DDR-054) canvas on
321
+ * the MAIN origin — where the normal
272
322
  * shell CSP is env-gated off — and the capture shim ACTIVELY primes+seeks every
273
323
  * `<video>`, so a canvas with `<Video src="http://169.254.169.254/…">` or comp
274
324
  * JS doing `fetch(internal)` would turn ⌘E into read-SSRF + exfil-via-artifact.
@@ -299,6 +349,26 @@ export function cspForCapture(): string {
299
349
  ].join('; ');
300
350
  }
301
351
 
352
+ /**
353
+ * Issue #126 — the chunked-upload routes refuse a request the browser itself
354
+ * marks as coming from another SITE. They are canvas-origin reachable by design
355
+ * (like `/_api/asset`, so no `sameOriginWrite`), but a blind `text/plain` POST
356
+ * from any page the user visits could otherwise open sessions it can never use
357
+ * and pin the session cap. The canvas iframe and the shell are same-origin or
358
+ * same-site (localhost ports, `canvas.<zone>`); a browser that sends no
359
+ * Fetch Metadata, and non-browser clients, are let through — the session cap,
360
+ * empty-session TTL and budget remain the backstop.
361
+ */
362
+ export function isCrossSiteFetch(req: Request): boolean {
363
+ return req.headers.get('sec-fetch-site') === 'cross-site';
364
+ }
365
+
366
+ const CROSS_SITE_CHUNK_REFUSAL = () =>
367
+ Response.json(
368
+ { ok: false, error: 'cross-site upload rejected' },
369
+ { status: 403, headers: { 'Cache-Control': 'no-store' } }
370
+ );
371
+
302
372
  /**
303
373
  * CSRF guard for the main-origin source-write routes (edit-css / edit-text /
304
374
  * edit-attr / reorder). Those routes are reachable only from the shell, which is
@@ -491,6 +561,8 @@ function designRootUrlBase(paths: { repoRoot: string; designRoot: string }): str
491
561
  return rel ? `/${rel.split('/').map(encodeURIComponent).join('/')}` : '';
492
562
  }
493
563
 
564
+ // Native separators throughout (#145): a `posix.join` here produced
565
+ // `C:\proj/.design/a.tsx` on Windows, which no later containment check matched.
494
566
  function safePathUnderRoot(reqUrl: string, repoRoot: string): string | null {
495
567
  let pathname: string;
496
568
  try {
@@ -498,10 +570,7 @@ function safePathUnderRoot(reqUrl: string, repoRoot: string): string | null {
498
570
  } catch {
499
571
  return null;
500
572
  }
501
- const sep = '/';
502
- const normalized = posix.normalize(posix.join(repoRoot, pathname));
503
- if (normalized !== repoRoot && !normalized.startsWith(repoRoot + sep)) return null;
504
- return normalized;
573
+ return resolveUrlPathUnder(pathname, repoRoot);
505
574
  }
506
575
 
507
576
  // `dist/` lives next to server.ts when running source-mode (bun run server.ts)
@@ -631,6 +700,20 @@ export interface ServeCanvasTestHooks {
631
700
  afterRead?: () => void | Promise<void>;
632
701
  }
633
702
 
703
+ /**
704
+ * A canvas that failed to build. V2-1.12 §5.8: in a project newer than this
705
+ * build, a canvas importing a `@maude/canvas-lib` export this build lacks says
706
+ * so first ("This canvas uses Maude 2. Update Maude to see it.").
707
+ */
708
+ function canvasBuildErrorResponse(err: unknown, ctx: Context): Response {
709
+ const msg = err instanceof Error ? err.message : String(err);
710
+ const line = canvasFormatLine(msg, formatGate(ctx, STAGED_FORMAT_GATE_OPTS));
711
+ return new Response(`Canvas build error: ${line ? `${line}\n\n` : ''}${msg}`, {
712
+ status: 500,
713
+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },
714
+ });
715
+ }
716
+
634
717
  export async function serveCanvasTsx(
635
718
  absPath: string,
636
719
  req: Request,
@@ -728,11 +811,7 @@ export async function serveCanvasTsx(
728
811
  headers: { 'Content-Type': 'text/plain; charset=utf-8' },
729
812
  });
730
813
  }
731
- const msg = err instanceof Error ? err.message : String(err);
732
- return new Response(`Canvas build error: ${msg}`, {
733
- status: 500,
734
- headers: { 'Content-Type': 'text/plain; charset=utf-8' },
735
- });
814
+ return canvasBuildErrorResponse(err, ctx);
736
815
  }
737
816
  // The signature against the freshly-parsed deps — this very edit may have
738
817
  // added or removed a `.css` import — stamped before the build (above).
@@ -951,11 +1030,7 @@ async function serveHistoricalCanvas(
951
1030
  if (oldest !== undefined) historicalCanvasCache.delete(oldest);
952
1031
  }
953
1032
  } catch (err) {
954
- const msg = err instanceof Error ? err.message : String(err);
955
- return new Response(`Canvas build error: ${msg}`, {
956
- status: 500,
957
- headers: { 'Content-Type': 'text/plain; charset=utf-8' },
958
- });
1033
+ return canvasBuildErrorResponse(err, ctx);
959
1034
  }
960
1035
  }
961
1036
  if (req.headers.get('if-none-match') === cached.etag) {
@@ -1015,7 +1090,7 @@ export function cacheControlFor(absPath: string): { cacheControl: string; addEta
1015
1090
  * cache, ours or anyone's in front of us, fetch it again. `serveFile` ignores
1016
1091
  * the query, so the old URL keeps working for anything that still asks for it.
1017
1092
  */
1018
- export async function serveIndexHtml(): Promise<Response> {
1093
+ export async function serveIndexHtml(extraHeaders: Record<string, string> = {}): Promise<Response> {
1019
1094
  const index = Bun.file(join(CLIENT_DIR, 'index.html'));
1020
1095
  if (!(await index.exists())) return new Response('Not found', { status: 404 });
1021
1096
  let html = await index.text();
@@ -1030,6 +1105,7 @@ export async function serveIndexHtml(): Promise<Response> {
1030
1105
  'Content-Type': 'text/html; charset=utf-8',
1031
1106
  'Cache-Control': 'no-cache',
1032
1107
  'X-Content-Type-Options': 'nosniff',
1108
+ ...extraHeaders,
1033
1109
  },
1034
1110
  });
1035
1111
  }
@@ -1170,8 +1246,38 @@ async function serveMediaFile(
1170
1246
  return new Response(file, { headers: base });
1171
1247
  }
1172
1248
 
1249
+ /**
1250
+ * V2-2.8 S6 — the committer list as the UNTRUSTED canvas origin (DDR-054) may
1251
+ * see it: names and commit counts, NO e-mail field. The in-canvas comment
1252
+ * composer only needs a name to suggest and insert `@firstname`; the trusted
1253
+ * shell keeps the full `git shortlog -sne` rows on the main origin. A name that
1254
+ * is itself an address keeps only the part before `@`, and rows that collapse
1255
+ * to one name merge (git keys a committer by name AND e-mail).
1256
+ * Decision `v2-2.8-s6-committers-projection` — a deliberate deviation from
1257
+ * V2-1.16 L15/L17 ("remove the route"): the feature stays, the leak goes.
1258
+ */
1259
+ export function canvasCommitters(
1260
+ rows: ReadonlyArray<{ name: string; commits: number }>
1261
+ ): Array<{ name: string; commits: number }> {
1262
+ const byName = new Map<string, number>();
1263
+ for (const row of rows) {
1264
+ const name = (String(row?.name ?? '').split('@')[0] ?? '').trim();
1265
+ if (!name) continue;
1266
+ byName.set(name, (byName.get(name) ?? 0) + (Number(row.commits) || 0));
1267
+ }
1268
+ return [...byName]
1269
+ .map(([name, commits]) => ({ name, commits }))
1270
+ .sort((a, b) => b.commits - a.commits);
1271
+ }
1272
+
1173
1273
  export interface Http {
1174
1274
  routes: Record<string, (req: Request) => Response | Promise<Response>>;
1275
+ /**
1276
+ * V2-2.8 S6 — handlers the canvas origins mount INSTEAD of the main-origin
1277
+ * one at the same path, because they answer a narrower projection
1278
+ * (server.ts `startCanvasServer` routes map). Same path, same allowlists.
1279
+ */
1280
+ canvasRoutes: Record<'/_api/git-committers', (req: Request) => Response | Promise<Response>>;
1175
1281
  fetch(req: Request): Promise<Response>;
1176
1282
  /**
1177
1283
  * T2 (9.1-A) — build the canvas mount-harness response. `applyCsp` adds the
@@ -1533,6 +1639,19 @@ export function createHttp(
1533
1639
  };
1534
1640
  }
1535
1641
 
1642
+ // V2-1.12 §5.6 — the format gate, STAGED: `newerOnly: true` gates only a
1643
+ // project newer than this build. One constant in format.ts, so the sync
1644
+ // runtime (sync/format-sync.ts) can never disagree with this gate.
1645
+ // (V2-2.18 1.x compat cut: the outbox and `maude migrate v2` route tables
1646
+ // of V2-2.14/V2-2.16 are v2-only and are not mounted here — a 1.x build
1647
+ // has no "Update project".)
1648
+ const gateNow = () => formatGate(ctx, STAGED_FORMAT_GATE_OPTS);
1649
+ /** What a read-only session may still write (the module allowlist). */
1650
+ const readOnlyAllowed = {
1651
+ exact: READ_ONLY_ALLOWED_WRITES as ReadonlySet<string>,
1652
+ patterns: READ_ONLY_ALLOWED_WRITE_PATTERNS as readonly RegExp[],
1653
+ };
1654
+
1536
1655
  const routes = {
1537
1656
  '/_health': () =>
1538
1657
  Response.json({
@@ -1759,6 +1878,12 @@ export function createHttp(
1759
1878
  .replace(/[^a-z0-9_-]/gi, '')
1760
1879
  .slice(0, 64);
1761
1880
  if (req.method === 'DELETE') {
1881
+ // V2-2.8 S2 — the same CSRF + loopback gate as PATCH below. Ungated, a
1882
+ // blind cross-site DELETE (or a DNS-rebound page) erased a transcript.
1883
+ if (!sameOriginWrite(req))
1884
+ return new Response('cross-origin write rejected', { status: 403 });
1885
+ if (!isTrustedRequestHost(req))
1886
+ return new Response('local request required (DNS-rebinding guard)', { status: 403 });
1762
1887
  const removed = id ? deleteChat(ctx.paths.designRoot, id) : false;
1763
1888
  return Response.json({ ok: removed }, { headers: { 'Cache-Control': 'no-store' } });
1764
1889
  }
@@ -1903,7 +2028,18 @@ export function createHttp(
1903
2028
  Response.json({
1904
2029
  ...ctx.cfg,
1905
2030
  canvasOrigin: ctx.canvasOrigin,
2031
+ // V2-1.12 §5.6 — readOnly is the role OR the format gate
2032
+ // (projectReadOnly covers both); the client shows WHY, and
2033
+ // `formatGate` drives the banner. Named one by one: the client
2034
+ // projection names every computed field (config-projection.test.ts).
1906
2035
  readOnly: projectReadOnly(req),
2036
+ formatVersion: projectFormat(ctx).value,
2037
+ formatGate: gateNow(),
2038
+ readOnlyReason: roleReadOnly(req) ? 'role' : gateNow() ? 'format' : null,
2039
+ // DDR-247 — the apps allowed to frame this studio for `?embed=1`. The
2040
+ // embed view posts its status ONLY to a parent on this list, never to
2041
+ // '*'. Public already: the same origins ride in the page's CSP header.
2042
+ ...(ctx.embedOrigins?.length ? { embedOrigins: ctx.embedOrigins } : {}),
1907
2043
  // WHICH RELEASE THIS IS. `/_config` reaches the browser in cloud mode,
1908
2044
  // so the bar for adding a field here is "would I publish it" — and a
1909
2045
  // version is the git tag, which is public. Nothing else rides along.
@@ -2141,8 +2277,15 @@ export function createHttp(
2141
2277
  );
2142
2278
  },
2143
2279
 
2144
- '/_index-data': async () =>
2145
- Response.json(await api.buildIndexData(), { headers: { 'Cache-Control': 'no-store' } }),
2280
+ // V2-2.8 S7 — the proxy-vouched role decides whether the Runtime group
2281
+ // (other members' session files) is listed; a desktop has no role.
2282
+ '/_index-data': async (req: Request) =>
2283
+ Response.json(
2284
+ await api.buildIndexData({
2285
+ role: isWorkspaceMode() ? req.headers.get('x-maude-role') : null,
2286
+ }),
2287
+ { headers: { 'Cache-Control': 'no-store' } }
2288
+ ),
2146
2289
 
2147
2290
  '/_system-data': async (req: Request) => {
2148
2291
  // DDR-048 — `?ds=<name>` scopes to one design system (per-DS tokens,
@@ -2195,7 +2338,7 @@ export function createHttp(
2195
2338
  // `.meta.json`, so a read-only session is refused here, in-handler,
2196
2339
  // where the two lanes are distinguishable.
2197
2340
  if (projectReadOnly(req) && 'layout' in body.patch) {
2198
- return readOnlyRefusalResponse();
2341
+ return readOnlyRefusalFor(req);
2199
2342
  }
2200
2343
  const next = await api.patchCanvasMeta(body.file, body.patch);
2201
2344
  if (!next) return new Response('Not found or rejected', { status: 404 });
@@ -4621,6 +4764,89 @@ export function createHttp(
4621
4764
  );
4622
4765
  },
4623
4766
 
4767
+ // Issue #126 — chunked upload for video/audio past the one-shot cap. Same
4768
+ // canvas-origin grant as `/_api/asset`, so all three routes are listed in
4769
+ // BOTH CANVAS_SAFE_API (below) and startCanvasServer's `routes` map
4770
+ // (server.ts) — Bun matches `routes` before `fetch`, so a one-list entry
4771
+ // 404s from the canvas iframe. Static paths + query params on purpose: a
4772
+ // dynamic segment would need a regex in every gate (here, the read-only
4773
+ // list, the hub manifest), and each regex is a hole nobody sees by reading
4774
+ // the list. The load-bearing caps live in api.ts (fixed chunk sizes, session
4775
+ // cap, budget reserved at start, sniff on the reassembled stream).
4776
+ '/_api/asset/chunk-start': async (req: Request) => {
4777
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4778
+ if (isCrossSiteFetch(req)) return CROSS_SITE_CHUNK_REFUSAL();
4779
+ const body = await readJson<{ totalSize?: unknown }>(req, 1024);
4780
+ if (!body) return new Response('body required', { status: 400 });
4781
+ const result = await api.startAssetChunkSession(body.totalSize);
4782
+ if (!result.ok) {
4783
+ return Response.json(
4784
+ { ok: false, error: result.error },
4785
+ { status: result.status, headers: { 'Cache-Control': 'no-store' } }
4786
+ );
4787
+ }
4788
+ return Response.json(
4789
+ { session: result.session, chunkBytes: result.chunkBytes, chunkCount: result.chunkCount },
4790
+ { status: 201, headers: { 'Cache-Control': 'no-store' } }
4791
+ );
4792
+ },
4793
+
4794
+ '/_api/asset/chunk': async (req: Request) => {
4795
+ const q = new URL(req.url).searchParams;
4796
+ if (isCrossSiteFetch(req)) return CROSS_SITE_CHUNK_REFUSAL();
4797
+ if (req.method === 'DELETE') {
4798
+ const result = await api.abortAssetChunkSession(q.get('session'));
4799
+ if (!result.ok) {
4800
+ return Response.json(
4801
+ { ok: false, error: result.error },
4802
+ { status: result.status, headers: { 'Cache-Control': 'no-store' } }
4803
+ );
4804
+ }
4805
+ return new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } });
4806
+ }
4807
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4808
+ // Fast reject of an honest oversize declaration; the streamed per-chunk
4809
+ // size check in api.writeAssetChunk is the authoritative gate.
4810
+ const declared = Number(req.headers.get('content-length') || '0');
4811
+ if (Number.isFinite(declared) && declared > ASSET_CHUNK_BYTES) {
4812
+ return Response.json(
4813
+ { ok: false, error: `chunk exceeds ${ASSET_CHUNK_BYTES} bytes` },
4814
+ { status: 413, headers: { 'Cache-Control': 'no-store' } }
4815
+ );
4816
+ }
4817
+ if (!req.body) return new Response('empty body', { status: 400 });
4818
+ const result = await api.writeAssetChunk(
4819
+ q.get('session'),
4820
+ q.get('index'),
4821
+ req.body as ReadableStream<Uint8Array>
4822
+ );
4823
+ if (!result.ok) {
4824
+ return Response.json(
4825
+ { ok: false, error: result.error },
4826
+ { status: result.status, headers: { 'Cache-Control': 'no-store' } }
4827
+ );
4828
+ }
4829
+ return new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } });
4830
+ },
4831
+
4832
+ '/_api/asset/chunk-finish': async (req: Request) => {
4833
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4834
+ if (isCrossSiteFetch(req)) return CROSS_SITE_CHUNK_REFUSAL();
4835
+ const result = await api.finishAssetChunkSession(
4836
+ new URL(req.url).searchParams.get('session')
4837
+ );
4838
+ if (!result.ok) {
4839
+ return Response.json(
4840
+ { ok: false, error: result.error },
4841
+ { status: result.status ?? 400, headers: { 'Cache-Control': 'no-store' } }
4842
+ );
4843
+ }
4844
+ return Response.json(
4845
+ { path: result.path },
4846
+ { status: 201, headers: { 'Cache-Control': 'no-store' } }
4847
+ );
4848
+ },
4849
+
4624
4850
  // DDR-167 (Phase 3 / T10) — hardened LOCAL-file SVG ingestion for the
4625
4851
  // in-app Brand-upload panel (T12). Privileged + main-origin-only (Decision
4626
4852
  // 4): absent from CANVAS_SAFE_API + startCanvasServer's routes map — the
@@ -5702,8 +5928,14 @@ export function createHttp(
5702
5928
  return new Response(null, { status: 204 });
5703
5929
  },
5704
5930
 
5705
- '/': () => serveIndexHtml(),
5706
- '/index.html': () => serveIndexHtml(),
5931
+ // DDR-247 — the studio page names who may frame it. It used to say
5932
+ // nothing, so any site could frame a signed-in studio (clickjacking).
5933
+ // Nothing legitimate frames it cross-origin: the desktop navigates its
5934
+ // webview to it top-level and every studio iframe is a canvas shell. The
5935
+ // shell origins stay listed; the configured embedders are added ONLY for
5936
+ // the read-only `?embed=1` view — the full studio is never theirs to frame.
5937
+ '/': (req: Request) => serveStudioPage(req),
5938
+ '/index.html': (req: Request) => serveStudioPage(req),
5707
5939
  } satisfies Record<string, (req: Request) => Response | Promise<Response>>;
5708
5940
 
5709
5941
  // Named `handleFallthrough`, not `fetch` — a same-named local function shadows
@@ -5785,10 +6017,18 @@ export function createHttp(
5785
6017
  // Query parameter ?canvas=<path-relative-to-designRoot> tells the shell
5786
6018
  // which canvas to import + mount. See plugins/design/templates/_shell.html.
5787
6019
  if (pathname === '/_canvas-shell.html' || pathname === '/_canvas-shell') {
6020
+ // V2-2.8 S9 (V2-1.16 L21) — only the MAIN listener reaches this branch
6021
+ // (the canvas and capture listeners answer the shell themselves, in
6022
+ // server.ts). While the split is on, every request here goes to the
6023
+ // read-only capture origin, bar Maude's own local harnesses (see
6024
+ // captureRedirect) — so what follows serves only those, and every
6025
+ // shell when the split is OFF.
6026
+ const toCapture = captureRedirect(req, url);
6027
+ if (toCapture) return toCapture;
5788
6028
  // The segregated canvas origin (server.ts) calls serveCanvasShell(true)
5789
6029
  // directly with CSP always on; on the legacy main origin the CSP stays
5790
6030
  // env-gated (MAUDE_CSP_POC) for the POC / backwards-compat. A capture
5791
- // render (?hide-chrome=1 — ⌘E export / screenshot shim) ALWAYS gets the
6031
+ // render (?hide-chrome=1) that still lands here ALWAYS gets the
5792
6032
  // network-locked capture CSP so it can't SSRF/exfil (attacker F1).
5793
6033
  const capture = url.searchParams.get('hide-chrome') === '1';
5794
6034
  return serveCanvasShell(process.env.MAUDE_CSP_POC === '1', capture);
@@ -5926,14 +6166,14 @@ export function createHttp(
5926
6166
  // A cell's disk is a cache: the bytes may be in the bucket and not
5927
6167
  // here. Only under the design root — the repo's other files are not
5928
6168
  // the file plane's.
5929
- if (`${fp}/`.startsWith(`${ctx.paths.designRoot}/`)) {
6169
+ if (isUnderOrEqual(fp, ctx.paths.designRoot)) {
5930
6170
  return materializedOr404(ctx.paths.designRoot, fp, req);
5931
6171
  }
5932
6172
  return new Response('Not found', { status: 404 });
5933
6173
  }
5934
6174
 
5935
6175
  const e = ext(fp);
5936
- const underDesignRoot = `${fp}/`.startsWith(`${ctx.paths.designRoot}/`);
6176
+ const underDesignRoot = isUnderOrEqual(fp, ctx.paths.designRoot);
5937
6177
  // .tsx under designRoot is a canvas — transpile + emit locator, return JS.
5938
6178
  if (e === '.tsx' && underDesignRoot) {
5939
6179
  return serveCanvasTsx(fp, req, ctx, join(ctx.paths.designRoot, '_locator.json'));
@@ -5984,6 +6224,81 @@ export function createHttp(
5984
6224
  }
5985
6225
  }
5986
6226
 
6227
+ function serveStudioPage(req: Request): Promise<Response> {
6228
+ let embed = false;
6229
+ try {
6230
+ embed = new URL(req.url).searchParams.get('embed') === '1';
6231
+ } catch {
6232
+ /* no usable URL — the ordinary page */
6233
+ }
6234
+ return serveIndexHtml({
6235
+ 'Content-Security-Policy': studioPageCsp(
6236
+ ctx.mainOrigin,
6237
+ embed ? (ctx.embedOrigins ?? []) : [],
6238
+ {
6239
+ embed,
6240
+ canvasOrigin: ctx.canvasOrigin,
6241
+ }
6242
+ ),
6243
+ });
6244
+ }
6245
+
6246
+ /**
6247
+ * V2-2.8 S9 (V2-1.16 L21, decision `v2-2.8-read-only-capture-origin`) —
6248
+ * headless renders (⌘E export via `canvasShellUrl`, `maude design
6249
+ * screenshot`, smoke, perf, canvas-rects, visual-sanity, older CLIs) load the
6250
+ * shell from the MAIN origin, where tenant canvas code (DDR-054) is
6251
+ * same-origin with every privileged route and passes `sameOriginWrite` +
6252
+ * `isTrustedRequestHost`. While the split is on, every such request gets a
6253
+ * 307 to the read-only capture origin (server.ts
6254
+ * `startCanvasServer(0, { capture: true })`) — same
6255
+ * route table, GET/HEAD only, no upgrades, strict CSP; the capture origin's
6256
+ * own `isCanvasSafeRoute` door then refuses whatever it must not serve.
6257
+ *
6258
+ * FAIL CLOSED: every main-origin shell request redirects. The shell builds
6259
+ * its module URL from the REQUEST's `designRel` + `canvas` (and loads
6260
+ * `tokens`/`components`/`layout`/`sha` too), so predicting which module a
6261
+ * URL will load and redirecting "only the dangerous ones" fails open on any
6262
+ * input the prediction misreads (V2-2.8 security review).
6263
+ *
6264
+ * The ONE exception (a named residual): Maude's own local harnesses, matched
6265
+ * exactly — `maude design draw-proof` (`_draw/<slug>.proof.tsx`) and
6266
+ * `photo-bg-remove` (`_photo/<slug>.bgremove.tsx`), with no parameter beyond
6267
+ * `canvas` and the server's own `designRel`. They live under DDR-115
6268
+ * runtime dirs the canvas-safe table refuses, and are generated on this
6269
+ * machine (never synced), so they keep rendering here exactly as before —
6270
+ * but only when the helper itself navigated there: Fetch Metadata `none`
6271
+ * (a browser-initiated `goto`/`open`) or absent (a non-browser client). A
6272
+ * page — another site, or a canvas on the canvas origin (same-site) —
6273
+ * steering a browser to a leftover harness URL is redirected like the rest.
6274
+ * Nothing is redirected when the split is off or in a cell (no capture
6275
+ * listener; a cell's proxy never routes the main-origin shell).
6276
+ */
6277
+ const LOCAL_HARNESS =
6278
+ /^_(?:draw\/[a-z0-9_][a-z0-9._-]*\.proof|photo\/[a-z0-9_][a-z0-9._-]*\.bgremove)\.tsx$/;
6279
+ function isLocalHarness(req: Request, url: URL): boolean {
6280
+ const site = req.headers.get('sec-fetch-site');
6281
+ if (site !== null && site !== 'none') return false;
6282
+ const params = [...url.searchParams.keys()];
6283
+ if (params.some((k) => k !== 'canvas' && k !== 'designRel')) return false;
6284
+ const canvases = url.searchParams.getAll('canvas');
6285
+ if (canvases.length !== 1 || !LOCAL_HARNESS.test(canvases[0] ?? '')) return false;
6286
+ const own = ctx.paths.designRel.replace(/^\/+|\/+$/g, '');
6287
+ const asked = url.searchParams.getAll('designRel');
6288
+ return asked.length === 0 || (asked.length === 1 && asked[0] === own);
6289
+ }
6290
+ function captureRedirect(req: Request, url: URL): Response | null {
6291
+ if (!ctx.captureOrigin) return null;
6292
+ if (isLocalHarness(req, url)) return null;
6293
+ return new Response(null, {
6294
+ status: 307,
6295
+ headers: {
6296
+ Location: `${ctx.captureOrigin}/_canvas-shell.html${url.search}`,
6297
+ 'Cache-Control': 'no-store',
6298
+ },
6299
+ });
6300
+ }
6301
+
5987
6302
  async function serveCanvasShell(applyCsp: boolean, capture = false): Promise<Response> {
5988
6303
  // `comment-mount.js` is versioned for the same reason as the studio page's
5989
6304
  // bundle (see `serveIndexHtml`): a fixed URL outlives a release in any
@@ -6008,7 +6323,11 @@ export function createHttp(
6008
6323
  // this is the SSRF/exfil boundary the export otherwise lacked (attacker F1).
6009
6324
  if (capture) headers['Content-Security-Policy'] = cspForCapture();
6010
6325
  else if (applyCsp)
6011
- headers['Content-Security-Policy'] = cspForCanvasShell(injected, ctx.mainOrigin);
6326
+ headers['Content-Security-Policy'] = cspForCanvasShell(
6327
+ injected,
6328
+ ctx.mainOrigin,
6329
+ ctx.embedOrigins
6330
+ );
6012
6331
  return new Response(injected, { headers });
6013
6332
  }
6014
6333
 
@@ -6051,8 +6370,13 @@ export function createHttp(
6051
6370
  '/_api/annotations', // annotation board (GET + whole-board PUT) — drives the collab bridge
6052
6371
  '/_api/annotations/ops', // DDR-242 annotation op batches (POST). MIRROR in server.ts routes.
6053
6372
  '/_api/asset', // Phase 23 — capped binary image upload (sniff+category cap+sha8 name+no-SVG)
6373
+ // Issue #126 — chunked video/audio upload (fixed chunks, session cap, budget
6374
+ // reserved at start, sniff on the reassembled stream). MIRROR in server.ts routes.
6375
+ '/_api/asset/chunk-start',
6376
+ '/_api/asset/chunk',
6377
+ '/_api/asset/chunk-finish',
6054
6378
  '/_api/photo-edit', // feature-photo-editor — PhotoEdit sidecar GET/PUT (cap-stack gated). MIRROR in server.ts routes.
6055
- '/_api/git-committers', // @mention autocomplete
6379
+ '/_api/git-committers', // @mention autocomplete — a no-e-mail projection here (V2-2.8 S6)
6056
6380
  '/_api/ai', // AI-activity banner
6057
6381
  '/_comments', // per-file comment list (renders pins)
6058
6382
  ]);
@@ -6140,7 +6464,7 @@ export function createHttp(
6140
6464
  // covers all three doors at once: the main-origin `routes` table, the
6141
6465
  // canvas-origin `routes` allowlist in server.ts (it references these same
6142
6466
  // handlers), and the dynamic-path `fetch` fall-through (comment replies).
6143
- function projectReadOnly(req?: Request): boolean {
6467
+ function roleReadOnly(req?: Request): boolean {
6144
6468
  // ---- Cloud Phase 27 A3/A4 (DDR-209): the role is PER SESSION ----------
6145
6469
  //
6146
6470
  // In a cell this process serves an owner and a viewer at the same time, so
@@ -6159,20 +6483,44 @@ export function createHttp(
6159
6483
  return ctx.cfg.linkedHub ? isHubReadOnly(ctx.cfg.linkedHub.url) : false;
6160
6484
  }
6161
6485
 
6486
+ /**
6487
+ * V2-1.12 §5.6 — read-only for the ROLE, or because this build does not
6488
+ * edit this project's FORMAT (format.ts `formatGate`: a 1.x build on a
6489
+ * format-2 project). Every in-handler `projectReadOnly` check therefore
6490
+ * covers both.
6491
+ */
6492
+ function projectReadOnly(req?: Request): boolean {
6493
+ return roleReadOnly(req) || gateNow() !== null;
6494
+ }
6495
+
6496
+ /** The refusal an in-handler check answers with: the format copy when the
6497
+ * format is the only reason, else the role copy. */
6498
+ function readOnlyRefusalFor(req: Request): Response {
6499
+ const gate = roleReadOnly(req) ? null : gateNow();
6500
+ return gate ? formatRefusalResponse(gate) : readOnlyRefusalResponse();
6501
+ }
6502
+
6162
6503
  function readOnlyRefusal(req: Request): Response | null {
6163
6504
  if (READ_ONLY_SAFE_METHODS.has(req.method)) return null;
6164
- if (!projectReadOnly(req)) return null;
6505
+ const role = roleReadOnly(req);
6506
+ const gate = gateNow();
6507
+ if (!role && !gate) return null;
6165
6508
  let pathname: string;
6166
6509
  try {
6167
6510
  pathname = new URL(req.url).pathname;
6168
6511
  } catch {
6169
- return readOnlyRefusalResponse();
6512
+ return readOnlyRefusalFor(req);
6170
6513
  }
6171
- if (READ_ONLY_ALLOWED_WRITES.has(pathname)) return null;
6514
+ // The format gate: per-user runtime, export, reports and sign-in still
6515
+ // work; comments are look-only (V2-1.12 §9 Q3).
6516
+ if (gate && !formatGateAllowsWrite(pathname, readOnlyAllowed))
6517
+ return formatRefusalResponse(gate);
6518
+ if (!role) return null;
6519
+ if (readOnlyAllowed.exact.has(pathname)) return null;
6172
6520
  // The dynamic half of the comment lane. An exact-match set cannot express
6173
6521
  // it, and leaving it out would mean a viewer may leave a comment but not
6174
6522
  // reply to one — a distinction nobody promised and nobody wants.
6175
- if (READ_ONLY_ALLOWED_WRITE_PATTERNS.some((re) => re.test(pathname))) return null;
6523
+ if (readOnlyAllowed.patterns.some((re) => re.test(pathname))) return null;
6176
6524
  return readOnlyRefusalResponse();
6177
6525
  }
6178
6526
 
@@ -6187,5 +6535,20 @@ export function createHttp(
6187
6535
  return readOnlyRefusal(req) ?? handleFallthrough(req);
6188
6536
  }
6189
6537
 
6190
- return { routes: guardedRoutes, fetch: guardedFetch, serveCanvasShell, isCanvasSafeRoute };
6538
+ const canvasRoutes: Http['canvasRoutes'] = {
6539
+ // V2-2.8 S6 — the @mention feed without e-mails (see canvasCommitters).
6540
+ '/_api/git-committers': async (req: Request) => {
6541
+ if (req.method !== 'GET') return new Response('Method not allowed', { status: 405 });
6542
+ const committers = canvasCommitters(await api.gitCommitters());
6543
+ return Response.json({ committers }, { headers: { 'Cache-Control': 'no-store' } });
6544
+ },
6545
+ };
6546
+
6547
+ return {
6548
+ routes: guardedRoutes,
6549
+ canvasRoutes,
6550
+ fetch: guardedFetch,
6551
+ serveCanvasShell,
6552
+ isCanvasSafeRoute,
6553
+ };
6191
6554
  }