-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Expand file tree
/
Copy pathimport-export-routes.ts
More file actions
1641 lines (1576 loc) · 65.8 KB
/
Copy pathimport-export-routes.ts
File metadata and controls
1641 lines (1576 loc) · 65.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Express, Response } from 'express';
import { PROJECT_EXPORT_MANIFEST_SCHEMA, isExportFormat } from '@open-design/contracts';
import nodePath from 'node:path';
import os from 'node:os';
import { isBlocked as isBlockedSystemDir } from './linked-dirs.js';
import type { RouteDeps } from './server-context.js';
import {
InlineAssetsLimitError,
MAX_INLINE_OWNER_BYTES,
inlineRelativeAssets,
type InlineAssetReader,
} from './inline-assets.js';
import {
buildDeckRenderInput,
buildScreenshotPdf,
buildScreenshotPptx,
decodeSlideDataUrls,
readSlideFiles,
type BuildDeckRenderInputOptions,
} from './deck-export.js';
import { readProjectFileVersion } from './project-file-versions.js';
import { authorizeReasoningEgress, sendReasoningEgressDenial } from './reasoning-egress.js';
import { sandboxImportedProjectRootUnavailableReason } from './sandbox-mode.js';
import { parseOrchestratorWorkspace } from './workspace-contract.js';
export interface RegisterImportRoutesDeps extends RouteDeps<'db' | 'http' | 'uploads' | 'node' | 'ids' | 'paths' | 'imports' | 'auth' | 'projectStore' | 'conversations' | 'projectFiles' | 'validation'> {}
export function registerImportRoutes(app: Express, ctx: RegisterImportRoutesDeps) {
const { db } = ctx;
const { sendApiError } = ctx.http;
const { importUpload } = ctx.uploads;
const { fs, path } = ctx.node;
const { randomId } = ctx.ids;
const { PROJECTS_DIR, RUNTIME_DATA_DIR_CANONICAL } = ctx.paths;
// A project root (imported folder OR a working-dir rebind) must not point at a
// system directory or a credential store. Binding it at $HOME / ~/.ssh / etc.
// would let the project file API read or delete the user's private keys and
// credentials. `isBlockedSystemDir` covers /etc, /proc, …; credential dirs use
// a prefix match; the home ROOT only exact-matches so legitimate subfolders
// (e.g. ~/Projects) stay usable. Shared by both entry points so neither can
// be used to bypass the other. Returns a rejection reason, or null if allowed.
async function blockedProjectRootReason(normalizedPath: string): Promise<string | null> {
let homeReal = os.homedir();
try { homeReal = await fs.promises.realpath(homeReal); } catch { /* keep as-is */ }
const credentialDirs = ['.ssh', '.aws', '.gnupg', '.kube', '.docker'].map((d) =>
path.join(homeReal, d),
);
const inCredentialDir = credentialDirs.some(
(dir) => normalizedPath === dir || normalizedPath.startsWith(dir + path.sep),
);
if (isBlockedSystemDir(normalizedPath) || normalizedPath === homeReal || inCredentialDir) {
return 'cannot use a system or credential directory as a project root';
}
return null;
}
const { importClaudeDesignZip, projectDir, detectEntryFile } = ctx.imports;
const {
consumedImportNonces,
desktopAuthSecret,
isDesktopAuthGateActive,
pruneExpiredImportNonces,
verifyDesktopImportToken,
} = ctx.auth;
const { getProject, insertProject, updateProject } = ctx.projectStore;
const { insertConversation } = ctx.conversations;
const { setTabs } = ctx.projectFiles;
const { validateProjectDesignSystemId } = ctx.validation;
app.post(
'/api/import/claude-design',
importUpload.single('file'),
async (req, res) => {
try {
if (!req.file)
return res.status(400).json({ error: 'zip file required' });
const originalName =
req.file.originalname || 'Claude Design export.zip';
if (!/\.zip$/i.test(originalName)) {
fs.promises.unlink(req.file.path).catch(() => {});
return res.status(400).json({ error: 'expected a .zip file' });
}
const id = randomId();
const now = Date.now();
const baseName =
originalName.replace(/\.zip$/i, '').trim() || 'Claude Design import';
const imported = await importClaudeDesignZip(
req.file.path,
projectDir(PROJECTS_DIR, id),
);
fs.promises.unlink(req.file.path).catch(() => {});
const project = insertProject(db, {
id,
name: baseName,
skillId: null,
designSystemId: null,
pendingPrompt: `Imported from Claude Design ZIP: ${originalName}. Continue editing ${imported.entryFile}.`,
metadata: {
kind: 'prototype',
importedFrom: 'claude-design',
entryFile: imported.entryFile,
sourceFileName: originalName,
},
createdAt: now,
updatedAt: now,
});
const cid = randomId();
insertConversation(db, {
id: cid,
projectId: id,
title: 'Imported Claude Design project',
createdAt: now,
updatedAt: now,
});
setTabs(db, id, [imported.entryFile], imported.entryFile);
res.json({
project,
conversationId: cid,
entryFile: imported.entryFile,
files: imported.files,
});
} catch (err: any) {
if (req.file?.path) fs.promises.unlink(req.file.path).catch(() => {});
res.status(400).json({ error: String(err) });
}
},
);
// Import an existing local folder as a project. The user picks a folder
// and OD works inside it directly: every write goes to metadata.baseDir.
// No copy, no shadow tree — the user owns the workspace and is
// responsible for their own version control (git, time machine, etc.),
// mirroring how Cursor / Claude Code / Aider behave.
// Replace an existing project's working directory in-place. Mirrors
// the same trust-gate, realpath, and data-dir checks as folder import,
// but updates metadata.baseDir on an existing project record.
app.post('/api/projects/:id/working-dir', async (req, res) => {
try {
const projectId = req.params.id;
const existing = getProject(db, projectId);
if (!existing) {
return sendApiError(res, 404, 'PROJECT_NOT_FOUND', 'project not found');
}
const { baseDir, orchestratorWorkspace } = req.body || {};
if (typeof baseDir !== 'string' || !baseDir.trim()) {
return sendApiError(res, 400, 'BAD_REQUEST', 'baseDir required');
}
const parsedOrchestratorWorkspace =
parseOrchestratorWorkspace(orchestratorWorkspace);
if (!parsedOrchestratorWorkspace.ok) {
return sendApiError(
res,
400,
'BAD_REQUEST',
parsedOrchestratorWorkspace.message,
);
}
const normalizedOrchestratorWorkspace = parsedOrchestratorWorkspace.value;
let trustedPickerImport = false;
if (isDesktopAuthGateActive()) {
const secret = desktopAuthSecret();
if (secret == null) {
return sendApiError(
res,
503,
'DESKTOP_AUTH_PENDING',
'desktop auth required but secret not yet registered',
{
details: { hint: 'restart desktop or wait for sidecar registration' },
retryable: true,
},
);
}
const headerValue = req.get('x-od-desktop-import-token');
const token = typeof headerValue === 'string' ? headerValue : '';
const now = Date.now();
pruneExpiredImportNonces(now);
const verification = verifyDesktopImportToken(
secret,
baseDir,
token,
now,
consumedImportNonces,
);
if (!verification.ok) {
return sendApiError(
res,
403,
'FORBIDDEN',
'desktop import token rejected',
{ details: { reason: verification.reason } },
);
}
consumedImportNonces.set(verification.nonce, verification.exp);
trustedPickerImport = true;
}
const trimmedInput = baseDir.trim();
if (!path.isAbsolute(path.normalize(trimmedInput))) {
return sendApiError(res, 400, 'BAD_REQUEST', 'baseDir must be absolute');
}
let normalizedPath: string;
try {
normalizedPath = await fs.promises.realpath(trimmedInput);
} catch {
return sendApiError(res, 400, 'BAD_REQUEST', 'folder not found');
}
let dirStat;
try {
dirStat = await fs.promises.lstat(normalizedPath);
} catch {
return sendApiError(res, 400, 'BAD_REQUEST', 'folder not found');
}
if (!dirStat.isDirectory()) {
return sendApiError(res, 400, 'BAD_REQUEST', 'path must be a directory');
}
if (path.parse(normalizedPath).root === normalizedPath) {
return sendApiError(res, 400, 'BAD_REQUEST', 'cannot point at the filesystem root');
}
if (
normalizedPath === RUNTIME_DATA_DIR_CANONICAL ||
normalizedPath.startsWith(RUNTIME_DATA_DIR_CANONICAL + path.sep)
) {
return sendApiError(res, 400, 'BAD_REQUEST', 'cannot point at the data directory');
}
const workingDirBlockReason = await blockedProjectRootReason(normalizedPath);
if (workingDirBlockReason) {
return sendApiError(res, 400, 'BAD_REQUEST', workingDirBlockReason);
}
const sandboxReason = normalizedOrchestratorWorkspace && trustedPickerImport
? null
: sandboxImportedProjectRootUnavailableReason(normalizedPath);
if (sandboxReason) {
return sendApiError(res, 400, 'BAD_REQUEST', sandboxReason);
}
const entryFile = await detectEntryFile(normalizedPath);
const existingMeta = existing.metadata ?? {};
const { orchestratorWorkspace: _existingOrchestratorWorkspace, ...preservedMeta } =
existingMeta;
const nextMeta = {
...preservedMeta,
kind: existingMeta.kind ?? 'prototype',
baseDir: normalizedPath,
importedFrom: 'folder' as const,
entryFile,
...(normalizedOrchestratorWorkspace
? { orchestratorWorkspace: normalizedOrchestratorWorkspace }
: {}),
...(trustedPickerImport ? { fromTrustedPicker: true as const } : {}),
};
const updated = updateProject(db, projectId, { metadata: nextMeta });
if (!updated) {
return sendApiError(res, 404, 'PROJECT_NOT_FOUND', 'project not found');
}
// Folder imports should land on Design Files so users can choose from
// the imported folder's artifacts. Persist an empty saved tab state so
// ProjectView does not auto-open the detected primary file on hydration.
setTabs(db, projectId, [], null);
/** @type {import('@open-design/contracts').ReplaceProjectWorkingDirResponse} */
const body = { project: updated, baseDir: normalizedPath, entryFile };
res.json(body);
} catch (err: any) {
sendApiError(res, 400, 'BAD_REQUEST', String(err?.message || err));
}
});
app.post('/api/import/folder', async (req, res) => {
try {
const { baseDir, name, skillId, designSystemId, orchestratorWorkspace } = req.body || {};
if (typeof baseDir !== 'string' || !baseDir.trim()) {
return sendApiError(res, 400, 'BAD_REQUEST', 'baseDir required');
}
const parsedOrchestratorWorkspace =
parseOrchestratorWorkspace(orchestratorWorkspace);
if (!parsedOrchestratorWorkspace.ok) {
return sendApiError(
res,
400,
'BAD_REQUEST',
parsedOrchestratorWorkspace.message,
);
}
const normalizedOrchestratorWorkspace = parsedOrchestratorWorkspace.value;
let trustedPickerImport = false;
if (isDesktopAuthGateActive()) {
const secret = desktopAuthSecret();
if (secret == null) {
return sendApiError(
res,
503,
'DESKTOP_AUTH_PENDING',
'desktop auth required but secret not yet registered',
{
details: { hint: 'restart desktop or wait for sidecar registration' },
retryable: true,
},
);
}
const headerValue = req.get('x-od-desktop-import-token');
const token = typeof headerValue === 'string' ? headerValue : '';
const now = Date.now();
pruneExpiredImportNonces(now);
const verification = verifyDesktopImportToken(
secret,
baseDir,
token,
now,
consumedImportNonces,
);
if (!verification.ok) {
return sendApiError(
res,
403,
'FORBIDDEN',
'desktop import token rejected',
{ details: { reason: verification.reason } },
);
}
consumedImportNonces.set(verification.nonce, verification.exp);
trustedPickerImport = true;
}
const trimmedInput = baseDir.trim();
if (!path.isAbsolute(path.normalize(trimmedInput))) {
return sendApiError(res, 400, 'BAD_REQUEST', 'baseDir must be absolute');
}
// Resolve symlinks once at import and persist the canonical path.
// Without this, a user-controlled symlink (e.g. ~/sneaky → /etc) at
// baseDir would let writeProjectFile escape the project sandbox at
// every later call: resolveSafe checks the *literal* baseDir, but
// the OS follows the symlink at write time. realpath() collapses
// the chain so the stored baseDir == what the kernel will write to.
let normalizedPath: string;
try {
normalizedPath = await fs.promises.realpath(trimmedInput);
} catch {
return sendApiError(res, 400, 'BAD_REQUEST', 'folder not found');
}
// realpath resolved → lstat the canonical path to ensure it's a
// real directory, not another symlink (defense-in-depth).
let dirStat;
try {
dirStat = await fs.promises.lstat(normalizedPath);
} catch {
return sendApiError(res, 400, 'BAD_REQUEST', 'folder not found');
}
if (!dirStat.isDirectory()) {
return sendApiError(res, 400, 'BAD_REQUEST', 'path must be a directory');
}
if (path.parse(normalizedPath).root === normalizedPath) {
return sendApiError(res, 400, 'BAD_REQUEST', 'cannot import the filesystem root');
}
// Prevent importing the data directory into itself (post-realpath so
// a symlink pointing into RUNTIME_DATA_DIR is also caught). Compare
// against the canonical alias because `normalizedPath` is the import
// folder's realpath; on macOS the data dir at /var/... resolves to
// /private/var/... and would never start-with the user-shaped path.
if (
normalizedPath === RUNTIME_DATA_DIR_CANONICAL ||
normalizedPath.startsWith(RUNTIME_DATA_DIR_CANONICAL + path.sep)
) {
return sendApiError(res, 400, 'BAD_REQUEST', 'cannot import the data directory');
}
const importBlockReason = await blockedProjectRootReason(normalizedPath);
if (importBlockReason) {
return sendApiError(res, 400, 'BAD_REQUEST', importBlockReason);
}
const sandboxReason = normalizedOrchestratorWorkspace && trustedPickerImport
? null
: sandboxImportedProjectRootUnavailableReason(normalizedPath);
if (sandboxReason) {
return sendApiError(res, 400, 'BAD_REQUEST', sandboxReason);
}
const id = randomId();
const now = Date.now();
const projectName =
typeof name === 'string' && name.trim()
? name.trim()
: path.basename(normalizedPath);
const entryFile = await detectEntryFile(normalizedPath);
const designSystemValidation = await validateProjectDesignSystemId(designSystemId);
if (!designSystemValidation.ok) {
return sendApiError(
res,
400,
designSystemValidation.code,
designSystemValidation.message,
);
}
const project = insertProject(db, {
id,
name: projectName,
skillId: skillId ?? null,
designSystemId: designSystemValidation.id,
pendingPrompt: null,
metadata: {
kind: 'prototype',
baseDir: normalizedPath,
importedFrom: 'folder',
entryFile,
...(normalizedOrchestratorWorkspace
? { orchestratorWorkspace: normalizedOrchestratorWorkspace }
: {}),
...(trustedPickerImport ? { fromTrustedPicker: true as const } : {}),
},
createdAt: now,
updatedAt: now,
});
const cid = randomId();
insertConversation(db, {
id: cid,
projectId: id,
title: `Imported from ${projectName}`,
createdAt: now,
updatedAt: now,
});
// Folder imports should land on Design Files so users can choose from
// the imported folder's artifacts. Persist an empty saved tab state so
// ProjectView does not auto-open the detected primary file on hydration.
setTabs(db, id, [], null);
/** @type {import('@open-design/contracts').ImportFolderResponse} */
const body = { project, conversationId: cid, entryFile };
res.json(body);
} catch (err: any) {
sendApiError(res, 400, 'BAD_REQUEST', String(err?.message || err));
}
});
}
export interface RegisterProjectExportRoutesDeps extends RouteDeps<'db' | 'http' | 'paths' | 'node' | 'ids' | 'projectStore' | 'exports' | 'projectFiles' | 'validation'> {}
export function registerProjectExportRoutes(app: Express, ctx: RegisterProjectExportRoutesDeps) {
const { db } = ctx;
const { sendApiError } = ctx.http;
const { PROJECTS_DIR, RUNTIME_DATA_DIR_CANONICAL } = ctx.paths;
const { fs, path } = ctx.node;
const { randomId } = ctx.ids;
const { getProject } = ctx.projectStore;
const { listFiles, readProjectFile, resolveProjectFilePath } = ctx.projectFiles;
const { isSafeId } = ctx.validation;
const {
buildProjectArchive,
buildBatchArchive,
buildDesktopPdfExportInput,
buildDesktopArtifactExportInput,
desktopPdfExporter,
desktopSlideRenderer,
desktopArtifactExporter,
daemonUrlRef,
sanitizeArchiveFilename,
} = ctx.exports;
function isNoSlideDeckRenderError(rendered: { ok: boolean; error?: string }): boolean {
return !rendered.ok && typeof rendered.error === 'string' && /no slide surfaces found/i.test(rendered.error);
}
function normalizeExportVersionId(raw: unknown): string | undefined {
if (typeof raw !== 'string') return undefined;
const value = raw.trim();
return value.length > 0 ? value : undefined;
}
async function readExportVersionSource(
projectId: string,
fileName: string,
versionId: string | undefined,
metadata: unknown,
): Promise<string | undefined> {
if (!versionId) return undefined;
const result = await readProjectFileVersion(
PROJECTS_DIR,
projectId,
fileName,
versionId,
metadata,
);
return result.content;
}
function screenshotRenderClientError(
rendered: { ok: boolean; error?: string; errorCode?: string },
format: 'pptx' | 'pdf' | 'image',
): { message: string; status: 400 | 422 } | null {
if (rendered.ok) return null;
if (rendered.errorCode === 'NO_SLIDES' || (format === 'pptx' && isNoSlideDeckRenderError(rendered))) {
return {
status: 422,
message: 'this artifact is not a slide deck — export it as PDF or an image instead',
};
}
if (rendered.errorCode === 'SLIDE_INDEX_OUT_OF_RANGE') {
return {
status: 422,
message: rendered.error || 'slide index is out of range',
};
}
if (rendered.errorCode === 'PAGE_TOO_TALL') {
return {
status: 422,
message: rendered.error || 'page is too tall to export as one image',
};
}
return null;
}
// Shared screenshot-export flow: render the deck to one PNG per slide via the
// desktop's Electron Chromium, then assemble the requested binary. Both the
// .pptx and raster-.pdf routes funnel through here. Like the PDF route, it
// requires the desktop runtime — there is no headless renderer in a bare
// daemon yet, so a web-only deployment gets a clear 501.
async function handleScreenshotExport(
res: Response,
format: 'pptx' | 'pdf' | 'image',
projectId: string,
body: any,
) {
let renderOutputDir: string | null = null;
try {
const { fileName, title, index, imageFormat, width, height } = body || {};
if (typeof fileName !== 'string' || fileName.length === 0) {
return sendApiError(res, 400, 'BAD_REQUEST', 'fileName required');
}
const project = getProject(db, projectId);
const metadata = project?.metadata ?? null;
const versionId = normalizeExportVersionId(body?.versionId);
const sourceHtml = await readExportVersionSource(projectId, fileName, versionId, metadata);
if (format === 'image' && imageFormat != null && imageFormat !== 'png' && imageFormat !== 'jpeg') {
return sendApiError(res, 400, 'BAD_REQUEST', 'imageFormat must be png or jpeg');
}
if (width != null && (typeof width !== 'number' || !Number.isFinite(width) || width <= 0)) {
return sendApiError(res, 400, 'BAD_REQUEST', 'width must be a positive number');
}
if (height != null && (typeof height !== 'number' || !Number.isFinite(height) || height <= 0)) {
return sendApiError(res, 400, 'BAD_REQUEST', 'height must be a positive number');
}
if (typeof desktopSlideRenderer !== 'function') {
if (format === 'image' && typeof desktopArtifactExporter === 'function') {
const input = await buildDesktopArtifactExportInput({
daemonUrl: daemonUrlRef.current,
fileName,
format,
metadata,
projectId,
projectsRoot: PROJECTS_DIR,
...(sourceHtml !== undefined ? { sourceHtml } : {}),
...(typeof title === 'string' ? { title } : {}),
...(typeof body?.deck === 'boolean' ? { deck: body.deck } : {}),
...(format === 'image' && imageFormat === 'jpeg' ? { imageFormat: 'jpeg' } : {}),
...(typeof width === 'number' ? { width } : {}),
...(typeof height === 'number' ? { height } : {}),
});
let result;
try {
result = await desktopArtifactExporter(input);
} catch (err: any) {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
`desktop renderer unavailable: ${err?.message || String(err)}`,
);
}
if (!result.ok || typeof result.path !== 'string') {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
result.error || 'desktop renderer returned no artifact',
);
}
try {
const buffer = await fs.promises.readFile(result.path);
const contentType =
result.mime || (imageFormat === 'jpeg' ? 'image/jpeg' : 'image/png');
const ext = contentType.includes('jpeg') || contentType.includes('jpg') ? 'jpg' : 'png';
const titleBase =
typeof title === 'string' && title.trim().length > 0
? title.trim()
: path.basename(fileName, path.extname(fileName)) || 'artifact';
const filename = `${sanitizeArchiveFilename(titleBase) || 'artifact'}.${ext}`;
const asciiFallback =
filename.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '_') || `artifact.${ext}`;
res.setHeader('Content-Type', contentType);
res.setHeader(
'Content-Disposition',
`attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
);
return res.send(buffer);
} finally {
await fs.promises.rm(result.path, { force: true }).catch(() => {});
}
}
return sendApiError(
res,
501,
'UPSTREAM_UNAVAILABLE',
'screenshot export is only available in the desktop runtime',
);
}
// Scratch dir under the daemon data root: the desktop renderer writes the
// rendered images here and returns their file paths, so large images never
// cross the JSON IPC channel as base64. The daemon owns it and deletes it in
// the finally below. Derived from RUNTIME_DATA_DIR per the data-dir contract.
const outputDir = path.join(RUNTIME_DATA_DIR_CANONICAL, 'export-render', randomId());
renderOutputDir = outputDir;
const renderOptions: BuildDeckRenderInputOptions = {
daemonUrl: daemonUrlRef.current,
fileName,
// Imported-folder projects keep their workspace under metadata.baseDir;
// thread it through so readProjectFile resolves the real file instead of
// 404ing on <data>/projects/:id.
metadata,
outputDir,
projectId,
projectsRoot: PROJECTS_DIR,
};
if (sourceHtml !== undefined) renderOptions.sourceHtml = sourceHtml;
if (typeof title === 'string') renderOptions.title = title;
if (typeof width === 'number') renderOptions.width = width;
if (typeof height === 'number') renderOptions.height = height;
// Page-vs-deck is the caller's call, not a `.slide`-count guess: PPTX is
// deck-only; image/PDF take the web's `effectiveDeck` signal so an ordinary
// page that happens to contain `.slide` markup is still captured full-page.
if (format === 'pptx') {
renderOptions.deck = true;
// Editable PPTX (native shapes/text via dom-to-pptx) vs the default
// screenshot PPTX (one image per slide).
if (body?.editable === true) renderOptions.editable = true;
} else if (typeof body?.deck === 'boolean') {
renderOptions.deck = body.deck;
}
// Image export = "the whole artifact as one picture": a deck becomes all
// slides stitched into one tall image; an ordinary page is its full-page
// capture. (A specific slide index is still honored if explicitly given.)
if (format === 'image') {
if (typeof index === 'number' && Number.isInteger(index) && index >= 0) {
renderOptions.index = index;
} else {
renderOptions.stitch = true;
}
}
// A non-deck page exported to PDF paginates into one PDF page per viewport
// (a long scrolling site becomes a readable multi-page PDF instead of one
// giant page). The desktop renderer uses JPEG only after it has decided
// page mode; auto-detected decks stay PNG for crisp slide text.
if (format === 'pdf' && body?.deck !== true) renderOptions.paginate = true;
// Image export defaults to PNG unless the caller explicitly asks for JPEG
// (CLI --image-format).
if (format === 'image' && imageFormat === 'jpeg') renderOptions.pageImageFormat = 'jpeg';
const tStart = Date.now();
const { input, title: resolvedTitle, defaultFilename } =
await buildDeckRenderInput(renderOptions);
// The renderer call is a cross-process IPC (requestJsonIpc, 600s). A
// missing desktop process, broken socket, or timeout is an upstream
// renderer outage — surface it as 502 UPSTREAM_UNAVAILABLE (matching the
// `!rendered.ok` branch below), not the outer 400 BAD_REQUEST which is for
// genuine request-validation / assembly errors.
let rendered;
try {
rendered = await desktopSlideRenderer(input);
} catch (err: any) {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
`desktop renderer unavailable: ${err?.message || String(err)}`,
);
}
const tRendered = Date.now();
const clientError = screenshotRenderClientError(rendered, format);
if (clientError) {
return sendApiError(res, clientError.status, 'BAD_REQUEST', clientError.message);
}
// Editable PPTX: the renderer wrote a finished .pptx (native shapes/text)
// to the scratch dir. Stream it directly — no image assembly. Confine the
// path to the scratch dir, same defense as the image handoff.
if (renderOptions.editable) {
if (!rendered.ok || typeof rendered.pptxFile !== 'string') {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
rendered.error || 'editable PPTX renderer returned no file',
);
}
const canonicalDir = await fs.promises.realpath(renderOutputDir).catch(() => renderOutputDir);
const realPptx = await fs.promises.realpath(rendered.pptxFile).catch(() => null);
if (!realPptx || (realPptx !== canonicalDir && !realPptx.startsWith(canonicalDir + path.sep))) {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
'renderer returned a pptx path outside the export scratch directory',
);
}
const pptxBuffer = await fs.promises.readFile(realPptx);
// eslint-disable-next-line no-console
console.info('[od-export] assemble', {
format: 'pptx-editable',
via: 'file',
bytes: pptxBuffer.length,
rendererMs: tRendered - tStart,
totalMs: Date.now() - tStart,
});
const editableName = `${defaultFilename}.pptx`;
const editableAscii =
editableName.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '_') || 'deck.pptx';
res.setHeader(
'Content-Type',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
);
res.setHeader(
'Content-Disposition',
`attachment; filename="${editableAscii}"; filename*=UTF-8''${encodeURIComponent(editableName)}`,
);
return res.send(pptxBuffer);
}
const hasFiles = Array.isArray(rendered.slideFiles) && rendered.slideFiles.length > 0;
const hasDataUrls = Array.isArray(rendered.slides) && rendered.slides.length > 0;
if (!rendered.ok || (!hasFiles && !hasDataUrls)) {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
rendered.error || 'desktop renderer returned no slides',
);
}
// PPTX is slide-based: an ordinary page (no `.slide` sections) has no
// slide model, so refuse rather than emit a one-giant-slide deck.
if (format === 'pptx' && rendered.mode === 'page') {
return sendApiError(
res,
422,
'BAD_REQUEST',
'this artifact is not a slide deck — export it as PDF or an image instead',
);
}
// Prefer the on-disk file handoff; fall back to base64 data URLs for older
// desktop builds that don't honor outputDir. Confine the handoff files to
// the canonical scratch dir before reading — a malformed renderer response
// must not make the daemon read & stream back arbitrary files (path
// traversal / symlink escape), since cleanup only removes renderOutputDir.
let images: Awaited<ReturnType<typeof readSlideFiles>>;
if (hasFiles) {
const canonicalDir = await fs.promises.realpath(renderOutputDir).catch(() => renderOutputDir);
const safeFiles: string[] = [];
for (const candidate of rendered.slideFiles as string[]) {
const real =
typeof candidate === 'string'
? await fs.promises.realpath(candidate).catch(() => null)
: null;
if (!real || (real !== canonicalDir && !real.startsWith(canonicalDir + path.sep))) {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
'renderer returned a slide path outside the export scratch directory',
);
}
safeFiles.push(real);
}
images = await readSlideFiles(safeFiles);
} else {
images = decodeSlideDataUrls(rendered.slides as string[]);
}
const tRead = Date.now();
let buffer: Buffer;
let contentType: string;
let ext: string;
if (format === 'pptx') {
// Derive the slide aspect from the rendered pixel dims so non-16:9 decks
// get a correctly-proportioned PPTX layout instead of a forced 16:9 one.
const aspect =
typeof rendered.width === 'number' &&
typeof rendered.height === 'number' &&
rendered.height > 0
? rendered.width / rendered.height
: undefined;
buffer = await buildScreenshotPptx(images, {
title: resolvedTitle,
...(aspect ? { aspect } : {}),
});
contentType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
ext = 'pptx';
} else if (format === 'pdf') {
buffer = await buildScreenshotPdf(images);
contentType = 'application/pdf';
ext = 'pdf';
} else {
// image: exactly one image (the requested slide, stitched deck, or whole
// page). A multi-image renderer result is a contract violation; never
// silently stream images[0], which would truncate a too-tall JPEG page to
// its first chunk.
if (images.length !== 1) {
return sendApiError(
res,
502,
'UPSTREAM_UNAVAILABLE',
`image renderer returned ${images.length} images for a single-image export`,
);
}
const first = images[0]!;
buffer = first.buffer;
contentType = first.jpeg ? 'image/jpeg' : 'image/png';
ext = first.jpeg ? 'jpg' : 'png';
}
// One-line export timing: renderer (desktop capture+encode+IPC) vs read
// (file handoff / base64 decode) vs assemble (pptx/pdf build). Pair with
// the desktop `[od-export] render` line for the full picture.
// eslint-disable-next-line no-console
console.info('[od-export] assemble', {
format,
via: hasFiles ? 'file' : 'dataurl',
slides: images.length,
bytes: buffer.length,
rendererMs: tRendered - tStart,
readMs: tRead - tRendered,
assembleMs: Date.now() - tRead,
totalMs: Date.now() - tStart,
});
const filename = `${defaultFilename}.${ext}`;
const asciiFallback =
filename.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '_') || `deck.${ext}`;
res.setHeader('Content-Type', contentType);
res.setHeader(
'Content-Disposition',
`attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
);
res.send(buffer);
} catch (err: any) {
const status = err && err.code === 'ENOENT' ? 404 : 400;
sendApiError(
res,
status,
status === 404 ? 'FILE_NOT_FOUND' : 'BAD_REQUEST',
String(err?.message || err),
);
} finally {
// Remove the scratch render dir regardless of success — these files are
// pure transient handoff, never served or persisted.
if (renderOutputDir) {
await fs.promises.rm(renderOutputDir, { recursive: true, force: true }).catch(() => {});
}
}
}
// Streams a ZIP of the project's on-disk tree so the "Download as .zip"
// share menu can hand the user the actual files they uploaded — e.g. the
// imported `ui-design/` folder — instead of a one-file snapshot of the
// rendered HTML. `root` scopes the archive to a subdirectory; without
// it, the whole project is packed.
app.get('/api/projects/:id/archive', async (req, res) => {
try {
const root = typeof req.query?.root === 'string' ? req.query.root : '';
const project = getProject(db, req.params.id);
const { buffer, baseName } = await buildProjectArchive(
PROJECTS_DIR,
req.params.id,
root,
project?.metadata,
);
const fallbackName = project?.name || req.params.id;
const fileSlug = sanitizeArchiveFilename(baseName || fallbackName) || 'project';
const filename = `${fileSlug}.zip`;
// RFC 5987 dance: legacy `filename=` carries an ASCII fallback, while
// `filename*=UTF-8''…` lets modern browsers pick up project names
// with non-ASCII characters (accents, CJK, etc.) without mojibake.
const asciiFallback =
filename.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '_') || 'project.zip';
res.setHeader('Content-Type', 'application/zip');
res.setHeader(
'Content-Disposition',
`attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
);
res.send(buffer);
} catch (err: any) {
const code = err && err.code;
const status = code === 'ENOENT' || code === 'ENOTDIR' ? 404 : 400;
sendApiError(
res,
status,
status === 404 ? 'FILE_NOT_FOUND' : 'BAD_REQUEST',
String(err?.message || err),
);
}
});
// Batch archive: accepts a list of file names and returns a ZIP of just
// those files. Used by the Design Files panel multi-select download.
app.post('/api/projects/:id/archive/batch', async (req, res) => {
try {
const { files } = req.body || {};
if (!Array.isArray(files) || files.length === 0) {
sendApiError(res, 400, 'BAD_REQUEST', 'files must be a non-empty array');
return;
}
const project = getProject(db, req.params.id);
const { buffer } = await buildBatchArchive(
PROJECTS_DIR,
req.params.id,
files,
project?.metadata,
);
const fileSlug = sanitizeArchiveFilename(project?.name || req.params.id) || 'project';
const filename = `${fileSlug}.zip`;
const asciiFallback =
filename.replace(/[^\x20-\x7e]/g, '_').replace(/"/g, '_') || 'project.zip';
res.setHeader('Content-Type', 'application/zip');
res.setHeader(
'Content-Disposition',
`attachment; filename="${asciiFallback}"; filename*=UTF-8''${encodeURIComponent(filename)}`,
);
res.send(buffer);
} catch (err: any) {
const code = err && err.code;
const status = code === 'ENOENT' ? 404 : 400;
sendApiError(
res,
status,
status === 404 ? 'FILE_NOT_FOUND' : 'BAD_REQUEST',
String(err?.message || err),
);
}
});
app.get('/api/projects/:id/export/manifest', async (req, res) => {
try {
if (!isSafeId(req.params.id)) {
return sendApiError(res, 400, 'BAD_REQUEST', 'invalid project id');
}
const project = getProject(db, req.params.id);
if (!project) {
return sendApiError(res, 404, 'PROJECT_NOT_FOUND', 'project not found');
}
const files = await listFiles(PROJECTS_DIR, req.params.id, {
metadata: project.metadata,
});
/** @type {import('@open-design/contracts').ProjectExportManifestResponse} */
const body = buildProjectExportManifestResponse({
project,
projectId: req.params.id,
files,
});
res.json(body);
} catch (err: any) {
sendApiError(res, 400, 'BAD_REQUEST', String(err?.message || err));
}
});
app.post('/api/projects/:id/export/pdf', async (req, res) => {
if (typeof desktopPdfExporter !== 'function') {
return sendApiError(
res,
501,
'UPSTREAM_UNAVAILABLE',
'desktop PDF export is only available in the desktop runtime',
);
}
try {
const { fileName, title, deck } = req.body || {};
if (typeof fileName !== 'string' || fileName.length === 0) {
return sendApiError(res, 400, 'BAD_REQUEST', 'fileName required');
}
const project = getProject(db, req.params.id);
const metadata = project?.metadata ?? null;
const versionId = normalizeExportVersionId(req.body?.versionId);
const sourceHtml = await readExportVersionSource(req.params.id, fileName, versionId, metadata);
const input = await buildDesktopPdfExportInput({
daemonUrl: daemonUrlRef.current,
deck: deck === true,
fileName,
metadata,
projectId: req.params.id,
projectsRoot: PROJECTS_DIR,
...(sourceHtml !== undefined ? { sourceHtml } : {}),
title: typeof title === 'string' ? title : undefined,
});
const result = await desktopPdfExporter(input);
res.json(result);
} catch (err: any) {
const status = err && err.code === 'ENOENT' ? 404 : 400;
sendApiError(
res,
status,
status === 404 ? 'FILE_NOT_FOUND' : 'BAD_REQUEST',
String(err?.message || err),
);
}
});
// Programmatic screenshot-based PPTX: render each deck slide to a pixel-perfect
// PNG and assemble a one-image-per-slide .pptx. Replaces the old "send a prompt
// to the agent and hope it runs python-pptx" path with a deterministic export.
app.post('/api/projects/:id/export/pptx', async (req, res) => {
await handleScreenshotExport(res, 'pptx', req.params.id, req.body);