@1agh/maude 1.7.1 → 1.8.1

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 (49) hide show
  1. package/apps/studio/acp/bridge.ts +1 -0
  2. package/apps/studio/acp/login-state.ts +1 -0
  3. package/apps/studio/acp/probe.ts +1 -0
  4. package/apps/studio/api.ts +412 -35
  5. package/apps/studio/asset-upload.ts +174 -0
  6. package/apps/studio/assets-s3.ts +37 -2
  7. package/apps/studio/bin/_pdf-playwright.mjs +22 -1
  8. package/apps/studio/bin/_png-playwright.mjs +20 -1
  9. package/apps/studio/bin/_region.mjs +92 -0
  10. package/apps/studio/canvas-build.ts +59 -4
  11. package/apps/studio/canvas-lib.tsx +48 -1
  12. package/apps/studio/canvas-shell.tsx +28 -4
  13. package/apps/studio/client/app.jsx +109 -22
  14. package/apps/studio/client/canvas-url.js +9 -0
  15. package/apps/studio/client/embed-view.jsx +284 -0
  16. package/apps/studio/client/embed.js +101 -0
  17. package/apps/studio/client/export-center.jsx +2 -0
  18. package/apps/studio/client/github.js +36 -3
  19. package/apps/studio/client/report-bug.jsx +8 -2
  20. package/apps/studio/context.ts +7 -0
  21. package/apps/studio/dist/client.bundle.js +2682 -2682
  22. package/apps/studio/dist/comment-mount.js +2 -2
  23. package/apps/studio/embed-origins.ts +52 -0
  24. package/apps/studio/export-dialog.tsx +55 -3
  25. package/apps/studio/exporters/format-scopes.ts +11 -3
  26. package/apps/studio/exporters/index.ts +17 -2
  27. package/apps/studio/exporters/jobs.ts +16 -8
  28. package/apps/studio/exporters/pdf.ts +10 -2
  29. package/apps/studio/exporters/png.ts +10 -2
  30. package/apps/studio/exporters/scope.ts +74 -3
  31. package/apps/studio/generation/runtime-probe.ts +1 -1
  32. package/apps/studio/git/service.ts +1 -0
  33. package/apps/studio/http.ts +186 -13
  34. package/apps/studio/input-router.tsx +7 -1
  35. package/apps/studio/path-containment.ts +72 -0
  36. package/apps/studio/paths.ts +14 -1
  37. package/apps/studio/read-only-mode.ts +53 -0
  38. package/apps/studio/server.ts +9 -0
  39. package/apps/studio/sync/index.ts +74 -13
  40. package/apps/studio/sync/park.ts +39 -0
  41. package/apps/studio/sync/presentation.ts +9 -3
  42. package/apps/studio/sync/writer-registry.ts +5 -0
  43. package/apps/studio/use-canvas-media-drop.tsx +8 -28
  44. package/apps/studio/whats-new.json +27 -0
  45. package/cli/commands/design.mjs +9 -2
  46. package/cli/commands/hub-workspace.mjs +25 -0
  47. package/cli/lib/workspace-plan.mjs +51 -0
  48. package/package.json +9 -9
  49. package/plugins/design/templates/_shell.html +58 -0
@@ -140,7 +140,7 @@ async function capturePdf(
140
140
  const args = [
141
141
  PDF_PLAYWRIGHT,
142
142
  '--url',
143
- canvasShellUrl(ctx, target.file),
143
+ canvasShellUrl(ctx, target.file, { annotations: target.annotations }),
144
144
  '--selector',
145
145
  target.cssPath,
146
146
  '--timeout',
@@ -148,7 +148,15 @@ async function capturePdf(
148
148
  '--scale',
149
149
  String(deviceScale),
150
150
  ];
151
- if (target.multi) args.push('--multi', '1', '--out-dir', outDir);
151
+ if (target.region) {
152
+ // Issue #125 — one page covering a world-plane region (whole canvas / selection box).
153
+ args.push(
154
+ '--region',
155
+ target.region === 'canvas' ? 'canvas' : JSON.stringify(target.region),
156
+ '--out',
157
+ path.join(outDir, `${target.canvasSlug}.pdf`)
158
+ );
159
+ } else if (target.multi) args.push('--multi', '1', '--out-dir', outDir);
152
160
  else {
153
161
  // Widen to the enclosing artboard only when scope.ts requested it
154
162
  // (artboard-via-descendant fallback). selection / artboard-by-id targets
@@ -92,7 +92,7 @@ async function captureElement(
92
92
  const args = [
93
93
  PNG_PLAYWRIGHT,
94
94
  '--url',
95
- canvasShellUrl(ctx, target.file),
95
+ canvasShellUrl(ctx, target.file, { annotations: target.annotations }),
96
96
  '--selector',
97
97
  target.cssPath,
98
98
  '--scale',
@@ -100,7 +100,15 @@ async function captureElement(
100
100
  '--timeout',
101
101
  String(options.timeoutSec ?? 12),
102
102
  ];
103
- if (target.multi) {
103
+ if (target.region) {
104
+ // Issue #125 — one image of a world-plane region (whole canvas / selection box).
105
+ args.push(
106
+ '--region',
107
+ target.region === 'canvas' ? 'canvas' : JSON.stringify(target.region),
108
+ '--out',
109
+ path.join(outDir, `${target.canvasSlug}.png`)
110
+ );
111
+ } else if (target.multi) {
104
112
  args.push('--multi', '1', '--out-dir', outDir);
105
113
  } else {
106
114
  // Only widen to the enclosing artboard when scope.ts asked for it
@@ -13,8 +13,21 @@ import type { Dirent } from 'node:fs';
13
13
  import { readdir } from 'node:fs/promises';
14
14
  import path from 'node:path';
15
15
 
16
- /** The four user-facing scope choices from the export dialog. */
17
- export type Scope = 'selection' | 'artboard' | 'canvas-as-separate' | 'project-raw';
16
+ /** The user-facing scope choices from the export dialog. */
17
+ export type Scope =
18
+ | 'selection'
19
+ | 'artboard'
20
+ | 'canvas-as-separate'
21
+ | 'canvas-whole'
22
+ | 'selection-bounds'
23
+ | 'project-raw';
24
+
25
+ /**
26
+ * A world-plane region captured as ONE image / page (issue #125): the whole
27
+ * canvas (every artboard + annotation element) or the union bounding box of a
28
+ * list of selected elements. Layout between artboards is kept as-is.
29
+ */
30
+ export type CaptureRegion = 'canvas' | { selectors: string[] };
18
31
 
19
32
  /**
20
33
  * What an adapter receives for each render unit. `element` targets carry a
@@ -44,6 +57,17 @@ export type Target =
44
57
  * directly and leave this `false`.
45
58
  */
46
59
  widen?: boolean;
60
+ /**
61
+ * Capture this region of the world plane as one unit instead of the
62
+ * element at `cssPath` (which then only gates "the canvas has mounted").
63
+ */
64
+ region?: CaptureRegion;
65
+ /**
66
+ * Render the annotation layer (the FigJam-style draw elements) into the
67
+ * capture. Comment pins stay hidden either way. Off unless the export
68
+ * options opt in with `includeAnnotations: true`.
69
+ */
70
+ annotations?: boolean;
47
71
  }
48
72
  | {
49
73
  kind: 'file-tree';
@@ -82,6 +106,8 @@ export interface ExportScopeHints {
82
106
  * the worker). The live dialog knows which file it is looking at; trust it.
83
107
  */
84
108
  canvasFile?: string | null;
109
+ /** Every selector of a multi-selection, for `selection-bounds`. */
110
+ selectionAll?: string[];
85
111
  }
86
112
 
87
113
  export interface ResolveScopeArgs {
@@ -119,9 +145,22 @@ function readHints(options: Record<string, unknown> | undefined): ExportScopeHin
119
145
  typeof options.artboardId === 'string' && options.artboardId ? options.artboardId : null;
120
146
  const canvasFile =
121
147
  typeof options.canvasFile === 'string' && options.canvasFile ? options.canvasFile : null;
122
- return { selection, artboardId, canvasFile };
148
+ // Bounded: every selector is evaluated in the capture page, and a job body
149
+ // is member-supplied — thousands of `:has()` selectors would pin a slot.
150
+ const selectionAll = Array.isArray(options.selectionAll)
151
+ ? (options.selectionAll as unknown[])
152
+ .filter(
153
+ (x): x is string => typeof x === 'string' && x.length > 0 && x.length <= MAX_SELECTOR_LEN
154
+ )
155
+ .slice(0, MAX_SELECTION_ALL)
156
+ : undefined;
157
+ return { selection, artboardId, canvasFile, selectionAll };
123
158
  }
124
159
 
160
+ /** Caps on `options.selectionAll` (security review, issue #125). */
161
+ export const MAX_SELECTION_ALL = 256;
162
+ const MAX_SELECTOR_LEN = 1024;
163
+
125
164
  const RAW_EXCLUDES = new Set([
126
165
  '_server.json',
127
166
  '_active.json',
@@ -224,6 +263,38 @@ export async function resolveScope(args: ResolveScopeArgs): Promise<Target[]> {
224
263
  const slug = slugify(activeFile, designRel);
225
264
  const sel = firstSelection(activeJson.selected);
226
265
 
266
+ if (scope === 'canvas-whole' || scope === 'selection-bounds') {
267
+ const annotations = args.options?.includeAnnotations === true;
268
+ const selectors = hints.selectionAll?.length
269
+ ? hints.selectionAll
270
+ : [hints.selection?.selector ?? sel?.selector ?? sel?.cssPath].filter(
271
+ (x): x is string => !!x
272
+ );
273
+ // No selection → the bounding box of "everything" is the whole canvas.
274
+ if (scope === 'canvas-whole' || !selectors.length) {
275
+ return [
276
+ {
277
+ kind: 'element',
278
+ cssPath: '[data-dc-screen]',
279
+ canvasSlug: slug,
280
+ file: activeFile,
281
+ region: 'canvas',
282
+ annotations,
283
+ },
284
+ ];
285
+ }
286
+ return [
287
+ {
288
+ kind: 'element',
289
+ cssPath: selectors[0],
290
+ canvasSlug: slug,
291
+ file: activeFile,
292
+ region: { selectors },
293
+ annotations,
294
+ },
295
+ ];
296
+ }
297
+
227
298
  if (scope === 'selection') {
228
299
  // Prefer the live submit-time snapshot over the persisted `_active.json`
229
300
  // selection — the dialog can clear the canvas selection before the bridged
@@ -33,7 +33,7 @@ export function cachedProbe(key: string, compute: () => boolean): boolean {
33
33
  export function hasCommandCached(cmd: string): boolean {
34
34
  return cachedProbe(`has:${cmd}`, () => {
35
35
  const finder = process.platform === 'win32' ? 'where' : 'which';
36
- return spawnSync(finder, [cmd], { stdio: 'ignore' }).status === 0;
36
+ return spawnSync(finder, [cmd], { stdio: 'ignore', windowsHide: true }).status === 0;
37
37
  });
38
38
  }
39
39
 
@@ -353,6 +353,7 @@ function runGit(
353
353
  return new Promise((resolveRun) => {
354
354
  const child = spawn('git', args, {
355
355
  cwd: dir,
356
+ windowsHide: true, // #141 — no console window per git call on Windows
356
357
  env: { ...process.env, GIT_TERMINAL_PROMPT: '0', ...env },
357
358
  stdio: ['ignore', 'pipe', 'pipe'],
358
359
  });
@@ -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';
@@ -111,6 +112,7 @@ import type { InspectRegistry } from './inspect.ts';
111
112
  import { canvasSlug, writeLocator } from './locator.ts';
112
113
  import { prepareManagedProject } from './managed-projects.ts';
113
114
  import { materializeMissing } from './materialize-client.ts';
115
+ import { isUnderOrEqual, resolveUrlPathUnder } from './path-containment.ts';
114
116
  import { BIN_DIR, DEV_SERVER_ROOT, MEDIA_DIR, STICKERS_DIR } from './paths.ts';
115
117
  import { createPhotoStore, PHOTO_EDIT_MAX_BYTES } from './photo-store.ts';
116
118
  import { probeReadiness } from './readiness.ts';
@@ -232,7 +234,35 @@ export function rootIdentity(root: string): string {
232
234
  return createHash('sha256').update(resolved, 'utf8').digest('hex').slice(0, 12);
233
235
  }
234
236
 
235
- export function cspForCanvasShell(html: string, mainOrigin?: string): string {
237
+ /**
238
+ * DDR-247 — the studio page's CSP. Always `frame-ancestors`; in the `?embed=1`
239
+ * view also `frame-src 'self' <canvas origin>`: the embed frames exactly one
240
+ * canvas, and a hostile canvas must not be able to navigate its own frame to a
241
+ * foreign origin (a look-alike sign-in page) inside someone else's app.
242
+ */
243
+ export function studioPageCsp(
244
+ mainOrigin: string | undefined,
245
+ embedOrigins: readonly string[],
246
+ { embed = false, canvasOrigin }: { embed?: boolean; canvasOrigin?: string } = {}
247
+ ): string {
248
+ const directives = [`frame-ancestors ${frameAncestors(mainOrigin, embedOrigins)}`];
249
+ if (embed) {
250
+ let canvas = '';
251
+ try {
252
+ canvas = canvasOrigin ? new URL(canvasOrigin).origin : '';
253
+ } catch {
254
+ /* unparseable — 'self' alone, the canvas then fails closed */
255
+ }
256
+ directives.push(`frame-src ${["'self'", canvas].filter(Boolean).join(' ')}`);
257
+ }
258
+ return directives.join('; ');
259
+ }
260
+
261
+ export function cspForCanvasShell(
262
+ html: string,
263
+ mainOrigin?: string,
264
+ embedOrigins: readonly string[] = []
265
+ ): string {
236
266
  const hashes: string[] = [];
237
267
  // Match inline <script> blocks only (no src=). `[^>]*` excludes any with src.
238
268
  const re = /<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi;
@@ -262,7 +292,9 @@ export function cspForCanvasShell(html: string, mainOrigin?: string): string {
262
292
  "form-action 'none'",
263
293
  "webrtc 'block'",
264
294
  ];
265
- if (mainOrigin) directives.push(`frame-ancestors 'self' ${mainOrigin}`);
295
+ // DDR-247 — an embedder of the studio page is an ANCESTOR of this frame too,
296
+ // and frame-ancestors checks every ancestor, so it is listed here as well.
297
+ if (mainOrigin) directives.push(`frame-ancestors ${frameAncestors(mainOrigin, embedOrigins)}`);
266
298
  return directives.join('; ');
267
299
  }
268
300
 
@@ -299,6 +331,26 @@ export function cspForCapture(): string {
299
331
  ].join('; ');
300
332
  }
301
333
 
334
+ /**
335
+ * Issue #126 — the chunked-upload routes refuse a request the browser itself
336
+ * marks as coming from another SITE. They are canvas-origin reachable by design
337
+ * (like `/_api/asset`, so no `sameOriginWrite`), but a blind `text/plain` POST
338
+ * from any page the user visits could otherwise open sessions it can never use
339
+ * and pin the session cap. The canvas iframe and the shell are same-origin or
340
+ * same-site (localhost ports, `canvas.<zone>`); a browser that sends no
341
+ * Fetch Metadata, and non-browser clients, are let through — the session cap,
342
+ * empty-session TTL and budget remain the backstop.
343
+ */
344
+ export function isCrossSiteFetch(req: Request): boolean {
345
+ return req.headers.get('sec-fetch-site') === 'cross-site';
346
+ }
347
+
348
+ const CROSS_SITE_CHUNK_REFUSAL = () =>
349
+ Response.json(
350
+ { ok: false, error: 'cross-site upload rejected' },
351
+ { status: 403, headers: { 'Cache-Control': 'no-store' } }
352
+ );
353
+
302
354
  /**
303
355
  * CSRF guard for the main-origin source-write routes (edit-css / edit-text /
304
356
  * edit-attr / reorder). Those routes are reachable only from the shell, which is
@@ -491,6 +543,8 @@ function designRootUrlBase(paths: { repoRoot: string; designRoot: string }): str
491
543
  return rel ? `/${rel.split('/').map(encodeURIComponent).join('/')}` : '';
492
544
  }
493
545
 
546
+ // Native separators throughout (#145): a `posix.join` here produced
547
+ // `C:\proj/.design/a.tsx` on Windows, which no later containment check matched.
494
548
  function safePathUnderRoot(reqUrl: string, repoRoot: string): string | null {
495
549
  let pathname: string;
496
550
  try {
@@ -498,10 +552,7 @@ function safePathUnderRoot(reqUrl: string, repoRoot: string): string | null {
498
552
  } catch {
499
553
  return null;
500
554
  }
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;
555
+ return resolveUrlPathUnder(pathname, repoRoot);
505
556
  }
506
557
 
507
558
  // `dist/` lives next to server.ts when running source-mode (bun run server.ts)
@@ -1015,7 +1066,7 @@ export function cacheControlFor(absPath: string): { cacheControl: string; addEta
1015
1066
  * cache, ours or anyone's in front of us, fetch it again. `serveFile` ignores
1016
1067
  * the query, so the old URL keeps working for anything that still asks for it.
1017
1068
  */
1018
- export async function serveIndexHtml(): Promise<Response> {
1069
+ export async function serveIndexHtml(extraHeaders: Record<string, string> = {}): Promise<Response> {
1019
1070
  const index = Bun.file(join(CLIENT_DIR, 'index.html'));
1020
1071
  if (!(await index.exists())) return new Response('Not found', { status: 404 });
1021
1072
  let html = await index.text();
@@ -1030,6 +1081,7 @@ export async function serveIndexHtml(): Promise<Response> {
1030
1081
  'Content-Type': 'text/html; charset=utf-8',
1031
1082
  'Cache-Control': 'no-cache',
1032
1083
  'X-Content-Type-Options': 'nosniff',
1084
+ ...extraHeaders,
1033
1085
  },
1034
1086
  });
1035
1087
  }
@@ -1904,6 +1956,10 @@ export function createHttp(
1904
1956
  ...ctx.cfg,
1905
1957
  canvasOrigin: ctx.canvasOrigin,
1906
1958
  readOnly: projectReadOnly(req),
1959
+ // DDR-247 — the apps allowed to frame this studio for `?embed=1`. The
1960
+ // embed view posts its status ONLY to a parent on this list, never to
1961
+ // '*'. Public already: the same origins ride in the page's CSP header.
1962
+ ...(ctx.embedOrigins?.length ? { embedOrigins: ctx.embedOrigins } : {}),
1907
1963
  // WHICH RELEASE THIS IS. `/_config` reaches the browser in cloud mode,
1908
1964
  // so the bar for adding a field here is "would I publish it" — and a
1909
1965
  // version is the git tag, which is public. Nothing else rides along.
@@ -4621,6 +4677,89 @@ export function createHttp(
4621
4677
  );
4622
4678
  },
4623
4679
 
4680
+ // Issue #126 — chunked upload for video/audio past the one-shot cap. Same
4681
+ // canvas-origin grant as `/_api/asset`, so all three routes are listed in
4682
+ // BOTH CANVAS_SAFE_API (below) and startCanvasServer's `routes` map
4683
+ // (server.ts) — Bun matches `routes` before `fetch`, so a one-list entry
4684
+ // 404s from the canvas iframe. Static paths + query params on purpose: a
4685
+ // dynamic segment would need a regex in every gate (here, the read-only
4686
+ // list, the hub manifest), and each regex is a hole nobody sees by reading
4687
+ // the list. The load-bearing caps live in api.ts (fixed chunk sizes, session
4688
+ // cap, budget reserved at start, sniff on the reassembled stream).
4689
+ '/_api/asset/chunk-start': async (req: Request) => {
4690
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4691
+ if (isCrossSiteFetch(req)) return CROSS_SITE_CHUNK_REFUSAL();
4692
+ const body = await readJson<{ totalSize?: unknown }>(req, 1024);
4693
+ if (!body) return new Response('body required', { status: 400 });
4694
+ const result = await api.startAssetChunkSession(body.totalSize);
4695
+ if (!result.ok) {
4696
+ return Response.json(
4697
+ { ok: false, error: result.error },
4698
+ { status: result.status, headers: { 'Cache-Control': 'no-store' } }
4699
+ );
4700
+ }
4701
+ return Response.json(
4702
+ { session: result.session, chunkBytes: result.chunkBytes, chunkCount: result.chunkCount },
4703
+ { status: 201, headers: { 'Cache-Control': 'no-store' } }
4704
+ );
4705
+ },
4706
+
4707
+ '/_api/asset/chunk': async (req: Request) => {
4708
+ const q = new URL(req.url).searchParams;
4709
+ if (isCrossSiteFetch(req)) return CROSS_SITE_CHUNK_REFUSAL();
4710
+ if (req.method === 'DELETE') {
4711
+ const result = await api.abortAssetChunkSession(q.get('session'));
4712
+ if (!result.ok) {
4713
+ return Response.json(
4714
+ { ok: false, error: result.error },
4715
+ { status: result.status, headers: { 'Cache-Control': 'no-store' } }
4716
+ );
4717
+ }
4718
+ return new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } });
4719
+ }
4720
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4721
+ // Fast reject of an honest oversize declaration; the streamed per-chunk
4722
+ // size check in api.writeAssetChunk is the authoritative gate.
4723
+ const declared = Number(req.headers.get('content-length') || '0');
4724
+ if (Number.isFinite(declared) && declared > ASSET_CHUNK_BYTES) {
4725
+ return Response.json(
4726
+ { ok: false, error: `chunk exceeds ${ASSET_CHUNK_BYTES} bytes` },
4727
+ { status: 413, headers: { 'Cache-Control': 'no-store' } }
4728
+ );
4729
+ }
4730
+ if (!req.body) return new Response('empty body', { status: 400 });
4731
+ const result = await api.writeAssetChunk(
4732
+ q.get('session'),
4733
+ q.get('index'),
4734
+ req.body as ReadableStream<Uint8Array>
4735
+ );
4736
+ if (!result.ok) {
4737
+ return Response.json(
4738
+ { ok: false, error: result.error },
4739
+ { status: result.status, headers: { 'Cache-Control': 'no-store' } }
4740
+ );
4741
+ }
4742
+ return new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } });
4743
+ },
4744
+
4745
+ '/_api/asset/chunk-finish': async (req: Request) => {
4746
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 });
4747
+ if (isCrossSiteFetch(req)) return CROSS_SITE_CHUNK_REFUSAL();
4748
+ const result = await api.finishAssetChunkSession(
4749
+ new URL(req.url).searchParams.get('session')
4750
+ );
4751
+ if (!result.ok) {
4752
+ return Response.json(
4753
+ { ok: false, error: result.error },
4754
+ { status: result.status ?? 400, headers: { 'Cache-Control': 'no-store' } }
4755
+ );
4756
+ }
4757
+ return Response.json(
4758
+ { path: result.path },
4759
+ { status: 201, headers: { 'Cache-Control': 'no-store' } }
4760
+ );
4761
+ },
4762
+
4624
4763
  // DDR-167 (Phase 3 / T10) — hardened LOCAL-file SVG ingestion for the
4625
4764
  // in-app Brand-upload panel (T12). Privileged + main-origin-only (Decision
4626
4765
  // 4): absent from CANVAS_SAFE_API + startCanvasServer's routes map — the
@@ -5702,8 +5841,14 @@ export function createHttp(
5702
5841
  return new Response(null, { status: 204 });
5703
5842
  },
5704
5843
 
5705
- '/': () => serveIndexHtml(),
5706
- '/index.html': () => serveIndexHtml(),
5844
+ // DDR-247 — the studio page names who may frame it. It used to say
5845
+ // nothing, so any site could frame a signed-in studio (clickjacking).
5846
+ // Nothing legitimate frames it cross-origin: the desktop navigates its
5847
+ // webview to it top-level and every studio iframe is a canvas shell. The
5848
+ // shell origins stay listed; the configured embedders are added ONLY for
5849
+ // the read-only `?embed=1` view — the full studio is never theirs to frame.
5850
+ '/': (req: Request) => serveStudioPage(req),
5851
+ '/index.html': (req: Request) => serveStudioPage(req),
5707
5852
  } satisfies Record<string, (req: Request) => Response | Promise<Response>>;
5708
5853
 
5709
5854
  // Named `handleFallthrough`, not `fetch` — a same-named local function shadows
@@ -5926,14 +6071,14 @@ export function createHttp(
5926
6071
  // A cell's disk is a cache: the bytes may be in the bucket and not
5927
6072
  // here. Only under the design root — the repo's other files are not
5928
6073
  // the file plane's.
5929
- if (`${fp}/`.startsWith(`${ctx.paths.designRoot}/`)) {
6074
+ if (isUnderOrEqual(fp, ctx.paths.designRoot)) {
5930
6075
  return materializedOr404(ctx.paths.designRoot, fp, req);
5931
6076
  }
5932
6077
  return new Response('Not found', { status: 404 });
5933
6078
  }
5934
6079
 
5935
6080
  const e = ext(fp);
5936
- const underDesignRoot = `${fp}/`.startsWith(`${ctx.paths.designRoot}/`);
6081
+ const underDesignRoot = isUnderOrEqual(fp, ctx.paths.designRoot);
5937
6082
  // .tsx under designRoot is a canvas — transpile + emit locator, return JS.
5938
6083
  if (e === '.tsx' && underDesignRoot) {
5939
6084
  return serveCanvasTsx(fp, req, ctx, join(ctx.paths.designRoot, '_locator.json'));
@@ -5984,6 +6129,25 @@ export function createHttp(
5984
6129
  }
5985
6130
  }
5986
6131
 
6132
+ function serveStudioPage(req: Request): Promise<Response> {
6133
+ let embed = false;
6134
+ try {
6135
+ embed = new URL(req.url).searchParams.get('embed') === '1';
6136
+ } catch {
6137
+ /* no usable URL — the ordinary page */
6138
+ }
6139
+ return serveIndexHtml({
6140
+ 'Content-Security-Policy': studioPageCsp(
6141
+ ctx.mainOrigin,
6142
+ embed ? (ctx.embedOrigins ?? []) : [],
6143
+ {
6144
+ embed,
6145
+ canvasOrigin: ctx.canvasOrigin,
6146
+ }
6147
+ ),
6148
+ });
6149
+ }
6150
+
5987
6151
  async function serveCanvasShell(applyCsp: boolean, capture = false): Promise<Response> {
5988
6152
  // `comment-mount.js` is versioned for the same reason as the studio page's
5989
6153
  // bundle (see `serveIndexHtml`): a fixed URL outlives a release in any
@@ -6008,7 +6172,11 @@ export function createHttp(
6008
6172
  // this is the SSRF/exfil boundary the export otherwise lacked (attacker F1).
6009
6173
  if (capture) headers['Content-Security-Policy'] = cspForCapture();
6010
6174
  else if (applyCsp)
6011
- headers['Content-Security-Policy'] = cspForCanvasShell(injected, ctx.mainOrigin);
6175
+ headers['Content-Security-Policy'] = cspForCanvasShell(
6176
+ injected,
6177
+ ctx.mainOrigin,
6178
+ ctx.embedOrigins
6179
+ );
6012
6180
  return new Response(injected, { headers });
6013
6181
  }
6014
6182
 
@@ -6051,6 +6219,11 @@ export function createHttp(
6051
6219
  '/_api/annotations', // annotation board (GET + whole-board PUT) — drives the collab bridge
6052
6220
  '/_api/annotations/ops', // DDR-242 annotation op batches (POST). MIRROR in server.ts routes.
6053
6221
  '/_api/asset', // Phase 23 — capped binary image upload (sniff+category cap+sha8 name+no-SVG)
6222
+ // Issue #126 — chunked video/audio upload (fixed chunks, session cap, budget
6223
+ // reserved at start, sniff on the reassembled stream). MIRROR in server.ts routes.
6224
+ '/_api/asset/chunk-start',
6225
+ '/_api/asset/chunk',
6226
+ '/_api/asset/chunk-finish',
6054
6227
  '/_api/photo-edit', // feature-photo-editor — PhotoEdit sidecar GET/PUT (cap-stack gated). MIRROR in server.ts routes.
6055
6228
  '/_api/git-committers', // @mention autocomplete
6056
6229
  '/_api/ai', // AI-activity banner
@@ -29,6 +29,8 @@
29
29
 
30
30
  import { type RefObject, useEffect } from 'react';
31
31
 
32
+ import { isEmbedCanvas } from './read-only-mode.ts';
33
+
32
34
  // ─────────────────────────────────────────────────────────────────────────────
33
35
  // Drag-vs-click threshold (T25)
34
36
  //
@@ -732,7 +734,11 @@ export function useInputRouter(opts: UseInputRouterOptions): void {
732
734
  );
733
735
  if (
734
736
  action.kind === 'tool' ||
735
- action.kind === 'escape' ||
737
+ // DDR-247 — in an embed, the router's catch-all Escape (drop the
738
+ // selection) does not CONSUME the key: left unprevented, it reaches
739
+ // the embed's relay and closes the app's dialog around it. Anything
740
+ // that genuinely owns Escape (a menu, an inline edit) still prevents it.
741
+ (action.kind === 'escape' && !isEmbedCanvas()) ||
736
742
  action.kind === 'undo' ||
737
743
  action.kind === 'redo'
738
744
  ) {
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Path containment that holds on Windows as well as POSIX (#145).
3
+ *
4
+ * The studio used to answer "is this file under that root?" with a string
5
+ * prefix — `${child}/`.startsWith(`${root}/`) — and to build the static route's
6
+ * file path with `posix.join(repoRoot, urlPath)`. On Windows the root is native
7
+ * (`C:\proj\.design`) while the joined path was mixed (`C:\proj/.design/a.tsx`),
8
+ * so the prefix never matched: every canvas `.tsx` skipped the transpile branch,
9
+ * went out as `text/plain`, and the iframe died on "Failed to fetch dynamically
10
+ * imported module".
11
+ *
12
+ * Both helpers take the `node:path` flavour as a parameter so the win32 case is
13
+ * testable from a Mac (`path.win32`); production callers use the default.
14
+ */
15
+ import nodePath from 'node:path';
16
+
17
+ type PathImpl = Pick<typeof nodePath, 'isAbsolute' | 'relative' | 'resolve' | 'sep'>;
18
+
19
+ /**
20
+ * True when `child` is `root` itself or lies inside it. `path.relative`, never a
21
+ * string prefix: a prefix compare also matches `/repo-evil` against `/repo`, and
22
+ * cannot see that `C:\proj\x` and `C:\proj/x` are the same file. Win32 compares
23
+ * case-insensitively, like the filesystem does — approximately: `toLowerCase`
24
+ * is Unicode folding, NTFS uses its own upcase table (U+212A KELVIN SIGN folds
25
+ * to `k` here and does not there). That can only matter for a look-alike
26
+ * sibling directory reached by `..`, which `resolveUrlPathUnder` refuses.
27
+ */
28
+ export function isUnderOrEqual(child: string, root: string, p: PathImpl = nodePath): boolean {
29
+ const fold = (s: string) => (p.sep === '\\' ? s.toLowerCase() : s);
30
+ const rel = p.relative(fold(root), fold(child));
31
+ if (rel === '') return true;
32
+ if (p.isAbsolute(rel)) return false; // another drive on win32
33
+ return rel !== '..' && !rel.startsWith(`..${p.sep}`);
34
+ }
35
+
36
+ /** DOS device names, with or without an extension (`NUL`, `con.css`, `con .css`, `COM1.tsx`). */
37
+ const WIN32_DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)\s*(\..*)?$/i;
38
+
39
+ /**
40
+ * Map an already-DECODED URL pathname (`/.design/ui/a.tsx`) onto a native
41
+ * absolute path under `root`, or null when it would leave `root`.
42
+ *
43
+ * On win32 a backslash or a colon in the URL is refused outright: the canvas-
44
+ * origin gate (`isCanvasSafeRoute`) normalizes with POSIX rules, so a `\` it
45
+ * reads as an ordinary character would become a separator here — `..%5c`
46
+ * climbing out of the design root while still under the repo (the DDR-060 A1/A2
47
+ * decode-mismatch class). A colon would name a drive or an NTFS stream. Neither
48
+ * can appear in a legitimate Windows file name anyway. Also refused on win32: a
49
+ * segment ending in `.` or a space (Windows silently trims it, so the name on
50
+ * disk differs from the one checked) and a DOS device name (`con.css`, `COM1`).
51
+ *
52
+ * A `..` segment is refused everywhere. The URL parser has already resolved
53
+ * every literal and `%2e` dot segment, so one that survives decoding came from
54
+ * an encoded `%2f` — never a link the studio builds, and the only way to reach
55
+ * a look-alike sibling directory through case folding.
56
+ */
57
+ export function resolveUrlPathUnder(
58
+ pathname: string,
59
+ root: string,
60
+ p: PathImpl = nodePath
61
+ ): string | null {
62
+ if (pathname.includes('\0')) return null;
63
+ const segments = pathname.split('/');
64
+ if (segments.includes('..')) return null;
65
+ if (p.sep === '\\') {
66
+ if (pathname.includes('\\') || pathname.includes(':')) return null;
67
+ if (segments.some((s) => s !== '' && s !== '.' && (/[. ]$/.test(s) || WIN32_DEVICE.test(s))))
68
+ return null;
69
+ }
70
+ const abs = p.resolve(root, `.${pathname.startsWith('/') ? '' : '/'}${pathname}`);
71
+ return isUnderOrEqual(abs, root, p) ? abs : null;
72
+ }
@@ -177,13 +177,26 @@ function isDevServerDir(dir: string): boolean {
177
177
  return existsSync(join(dir, 'http.ts'));
178
178
  }
179
179
 
180
+ /**
181
+ * `\\?\C:\x` → `C:\x` and `\\?\UNC\srv\share` → `\\srv\share`; anything else
182
+ * unchanged. Mirrors `strip_verbatim` in apps/desktop/src-tauri/src/win_process.rs.
183
+ */
184
+ export function stripWin32Verbatim(p: string): string {
185
+ if (p.startsWith('\\\\?\\UNC\\')) return `\\\\${p.slice(8)}`;
186
+ if (/^\\\\\?\\[a-zA-Z]:/.test(p)) return p.slice(4);
187
+ return p;
188
+ }
189
+
180
190
  function resolveDevServerRoot(): string {
181
191
  // (0) Explicit override. Used when the runtime can't be found by walk-up — e.g.
182
192
  // the Tauri desktop bundle (DDR-106) ships apps/studio/ as an app resource and
183
193
  // sets MAUDE_DEV_SERVER_ROOT to it, because the sidecar binary sits alone in
184
194
  // Maude.app/Contents/MacOS/ with no apps/studio/ up-tree (the bundle ships the
185
195
  // full source, so `http.ts` is present at the resource root).
186
- const override = process.env.MAUDE_DEV_SERVER_ROOT;
196
+ // #141 — a verbatim `\\?\C:\…` root (what Tauri's resource_dir is on Windows)
197
+ // propagates into the ACP adapter's entry path, and `node \\?\C:\…` cannot
198
+ // start a script (nodejs/node#62446). The shell strips it; so do we.
199
+ const override = stripWin32Verbatim(process.env.MAUDE_DEV_SERVER_ROOT ?? '');
187
200
  // Require the same `http.ts` anchor walk-up uses (not merely a `dist/` dir) so a
188
201
  // planted dist-only directory can't hijack the runtime root (security review F4).
189
202
  if (override && !isVirtualBunfsPath(override) && isDevServerDir(override)) {