Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: download and validate portable Code Animation packages (#9385)
[._.]/ Adam Eivya75445f3032e
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsxindex b421d77aab..b390e111b6 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { Circle, Clapperboard, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';import { Link } from 'react-router';import toast from '../ui/Toast';-import { cancelCodeAnimationExport, exportCodeAnimation, uploadGalleryVideo } from '../../services/api';+import { cancelCodeAnimationExport, exportCodeAnimation, getCodeAnimationPackage, uploadGalleryVideo } from '../../services/api';import { useSseProgress } from '../../hooks/useSseProgress';import { downloadBlob } from '../../lib/downloadBlob';@@ -85,6 +85,7 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlconst [recordProgress, setRecordProgress] = useState(0);const [video, setVideo] = useState(null);const [saving, setSaving] = useState(false);+ const [packageDownloading, setPackageDownloading] = useState(false);const recordTimerRef = useRef(null);// Frame-exact export runs server-side on the media queue; its progress and// result stream from the composition job's SSE channel.@@ -222,6 +223,17 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl}};+ const handleDownloadPackage = async () => {+ if (!jobId || packageDownloading) return;+ setPackageDownloading(true);+ const pkg = await getCodeAnimationPackage(jobId, { silent: true }).catch((error) => {+ toast.error(error.message || 'Failed to download the package');+ return null;+ });+ setPackageDownloading(false);+ if (pkg) downloadBlob(JSON.stringify(pkg, null, 2), `${fileBase}.code-animation.json`, 'application/json');+ };+if (!html) return null;const aspect = frame?.width && frame?.height ? `${frame.width} / ${frame.height}` : '16 / 9';@@ -309,6 +321,14 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl><FileCode2 className="h-4 w-4" /> Download HTML</button>+ {jobId && (+ <button type="button" onClick={handleDownloadPackage} disabled={packageDownloading}+ title="Portable source and brief with integrity hashes; selected external audio is not included"+ className={BUTTON_SECONDARY}>+ {packageDownloading ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}+ Download package+ </button>+ )}<span className="text-xs text-gray-500">{meta ? 'Animation ready' : 'Waiting for the animation to report ready…'}{audio.status === 'failed' ? ' · audio track failed to load' : ''}diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsxindex cc97f1d604..6c5339cb9a 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx@@ -3,11 +3,13 @@ import { act, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';-vi.mock('../../services/api', () => ({ uploadGalleryVideo: vi.fn(), exportCodeAnimation: vi.fn(), cancelCodeAnimationExport: vi.fn() }));+vi.mock('../../services/api', () => ({ uploadGalleryVideo: vi.fn(), exportCodeAnimation: vi.fn(), cancelCodeAnimationExport: vi.fn(), getCodeAnimationPackage: vi.fn() }));+vi.mock('../../lib/downloadBlob', () => ({ downloadBlob: vi.fn() }));vi.mock('../../hooks/useSseProgress', () => ({ useSseProgress: vi.fn(() => ({ latest: null })) }));import CodeAnimationPreview, { prepareAnimationHtml } from './CodeAnimationPreview';-import { exportCodeAnimation } from '../../services/api';+import { exportCodeAnimation, getCodeAnimationPackage } from '../../services/api';+import { downloadBlob } from '../../lib/downloadBlob';import { useSseProgress } from '../../hooks/useSseProgress';const MESSAGES = { ready: 'ca:ready', record: 'ca:record', recorded: 'ca:recorded', progress: 'ca:progress', error: 'ca:error' };@@ -55,6 +57,17 @@ describe('CodeAnimationPreview', () => {afterEach(() => vi.unstubAllGlobals());+ it('downloads the saved portable package through the public API', async () => {+ const user = userEvent.setup();+ const pkg = { schemaVersion: 1, revisionHash: 'example-digest', files: [] };+ getCodeAnimationPackage.mockResolvedValue(pkg);+ renderPreview({ jobId: 'job-1' });+ await user.click(screen.getByRole('button', { name: 'Download package' }));+ expect(getCodeAnimationPackage).toHaveBeenCalledWith('job-1', { silent: true });+ expect(downloadBlob).toHaveBeenCalledWith(JSON.stringify(pkg, null, 2), 'lantern.code-animation.json', 'application/json');+ expect(screen.getByRole('button', { name: 'Download package' })).toBeEnabled();+ });+it('runs the page in a scripts-only sandbox and records through the postMessage handshake', async () => {const user = userEvent.setup();renderPreview();diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 217be4ef46..007d76b5b5 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -115,7 +115,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. || `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). || `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |-| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled LLM prompt building, a persistent generation gallery, and provider jobs (start + poll for the HTML). |+| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery, provider jobs, frame-exact export, and portable package download/data-only validation. || `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. || `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL, the full-resolution OBJ download URL, and the AR Quick Look USDZ upload/download pair. || `apiPipeline.js` | Pipeline (issues + stages + canon; series names and index summaries). |diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 14e9562501..b8b260c1ee 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -33,6 +33,16 @@ export const listCodeAnimationJobPage = ({ cursor, signal, limit = 50 } = {}) =>export const getCodeAnimationJob = (id, options) =>request(`/code-animation/generate/${encodeURIComponent(id)}`, options);+export const getCodeAnimationPackage = (id, options) =>+ request(`/code-animation/${encodeURIComponent(id)}/package`, options);++// Checks package data/integrity only; no file staging or execution.+export const validateCodeAnimationPackage = (pkg, options) => request('/code-animation/packages/validate', {+ method: 'POST',+ body: JSON.stringify(pkg),+ ...options,+});+// Queue a frame-exact MP4 export; returns { jobId, notes }. Progress streams// from /api/html-composition/:jobId/events.export const exportCodeAnimation = (id, options) => request(`/code-animation/${encodeURIComponent(id)}/export`, {diff --git a/docs/API.md b/docs/API.mdindex 61a989e1ef..33745cae0b 100644--- a/docs/API.md+++ b/docs/API.md@@ -768,7 +768,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/games` | Game projects || `/api/sprites` | Sprite catalog / export || `/api/threejs-models` | Procedural Three.js models |-| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery, generated HTML retrieval, and frame-exact MP4 export (`POST /:id/export` → HTML-composition media job) |+| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery, generated HTML retrieval, frame-exact MP4 export (`POST /:id/export` → HTML-composition media job), portable source download (`GET /:id/package`), and data-only package validation (`POST /packages/validate`; [contract](CODE_ANIMATION_PACKAGES.md)) || `/api/image-to-3d` | Image-to-3D conversion || `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models || `/api/privacy` | PII vault / trusted-org / broker opt-out |diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.mdnew file mode 100644index 0000000000..f49ac983b7--- /dev/null+++ b/docs/CODE_ANIMATION_PACKAGES.md@@ -0,0 +1,78 @@+# Code Animation packages++Completed animations offer **Download package** beside Download HTML. The JSON+contains the exact saved HTML, its brief and frame settings, and integrity hashes.+It is a portable handoff to an external authoring harness. The existing preview+and MP4 export continue to use the saved job.++`GET /api/code-animation/:id/package` downloads a version-1 package. The job must+be completed; missing jobs return 404 and unfinished jobs return 409. A source+above the 2 MiB per-file package limit returns 422; Download HTML remains available. Local+provider ids, universe/mood-board pointers, upload URLs, reference attachments,+and prompt text are excluded. Source and artist-authored brief text are included;+review those before sharing a package. Selected external audio is declared but+its bytes are not included. Procedural Web Audio is declared as live sound with+no offline soundtrack. Unrecorded seed and execution settings remain `null`.++`POST /api/code-animation/packages/validate` accepts the package directly as its+JSON body. It returns `{ schemaVersion, revisionHash, renderer, fileCount,+totalBytes, executed: false }` or a 400 validation error. This is an integrity+check: it does not stage or execute code, install dependencies, call a provider,+create a project, or modify a saved animation. A valid Blender package does not+establish Blender readiness, code safety, a rendered result, or passing review.+Durable production import, execution, and rendering are separate implementation+slices of #9383.++## Version-1 envelope++All fields below are required. Unknown fields and unsupported versions are+rejected. There are no silent defaults during validation.++| Field | Contract |+|---|---|+| `schemaVersion` | Integer `1` |+| `manifest.title` | At most 200 characters |+| `manifest.brief` | `concept` (6,000 characters), `cast` (4,000), `onScreenText` (4,000) |+| `manifest.styleGuide` | At most 16,000 characters; empty is permitted |+| `manifest.renderer` | `kind`: `browser` or `blender`; nonempty `version` (128 characters); `engine`: string (128 characters) or `null`. Describes the renderer; never selects a host executable. Legacy exports use `code-animation-html-v1`, a runtime contract version. |+| `manifest.format` | Even `width`/`height` from 2 to 8,192; integer `fps` from 1 to 60; positive `durationSeconds` up to 180 |+| `manifest.seed` | Unsigned 32-bit integer or `null` |+| `manifest.entrypoints` | One to three `{ role, path }` entries; roles `scene`, `preview`, `render` are unique. Every path names a bundled file. Source language is renderer-specific. |+| `manifest.assets` | Up to 64 bundled file paths |+| `manifest.shots` | Up to 128 `{ label, startSeconds, endSeconds }` entries; positive intervals within the film |+| `manifest.events` | Up to 512 `{ label, atSeconds }` entries within the film. Shot/event labels have a 200-character limit. |+| `manifest.audio` | `{ kind: 'silence' }`, `{ kind: 'procedural', notes }`, `{ kind: 'external', notes }`, or `{ kind: 'file', path }`. Notes have a 1,500-character limit; file audio must be bundled. |+| `manifest.execution` | `requested` and `effective`, each `null` or `{ harness, connection, mode, model, effort }`. Strings are bounded (128 characters, model 256); unknown values remain `null`; mode is `api`, `cli`, or `tui`; effort uses the shared provider ladder. Imported metadata is a claim, never verified execution evidence. |+| `files` | One to 64 `{ path, encoding, content, sha256 }` entries. Encoding is `utf8` or canonical padded `base64`; SHA-256 is lowercase hex of decoded bytes. |+| `revisionHash` | Lowercase SHA-256 binding manifest, version, paths and file digests |++Paths are at most 240 characters, relative, slash-separated, and contain only+ASCII letters, digits, `.`, `_`, and `-`. Each segment starts with a letter or+digit and cannot end in a dot. Empty segments, dot segments, hidden paths,+absolute paths, backslashes, drive/URL prefixes, escaped separators and Windows+device names are refused. Duplicate paths, case collisions, and file/parent+collisions are refused on every platform. References must match the exact path.++Each decoded file is limited to 2 MiB and all decoded files together to 8 MiB.+Malformed or noncanonical base64 and invalid UTF-8 text are refused. File bytes+are checked against their digest before the validation can succeed.++The revision hash is SHA-256 over UTF-8 canonical JSON for:++```js+{+ schemaVersion,+ manifest,+ files: files.map(({ path, sha256 }) => ({ path, sha256 }))+ .sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)+}+```++Canonical JSON sorts object keys recursively, uses compact JSON serialization,+and preserves array order. The same bytes encoded as UTF-8 or base64 and the+same metadata in another key order retain the revision hash. File order does+not matter; timing/entrypoint/asset order does. Changing source bytes or manifest+settings changes the revision hash. The leaf contract in+`server/lib/codeAnimationPackage.js` provides the shared schema and builder.+No package is persisted by these endpoints, so this slice needs no new store,+seed, migration, or federation channel.diff --git a/docs/README.md b/docs/README.mdindex ca4c17a5a1..0a6f1abcb2 100644--- a/docs/README.md+++ b/docs/README.md@@ -9,6 +9,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| Doc | Covers ||-----|--------|| [HTML_COMPOSITIONS.md](./HTML_COMPOSITIONS.md) | Seekable HTML scenes rendered offline to MP4 through hidden managed-browser targets |+| [CODE_ANIMATION_PACKAGES.md](./CODE_ANIMATION_PACKAGES.md) | Versioned portable Code Animation source/brief packages and non-executing validation || [ARCHITECTURE.md](./ARCHITECTURE.md) | System design: React client, Express server, PM2 satellites, PostgreSQL + `data/` files || [features/catalog-ingest.md](./features/catalog-ingest.md) | Catalog extraction graph, context budgets, coverage, and review draft contract || [API.md](./API.md) | REST endpoints, complete route-domain index, Socket.IO events |diff --git a/server/lib/README.md b/server/lib/README.mdindex bb94869b25..839f02dd54 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -27,6 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `appDeployFlags.js` | Shared allowlist of flags PortOS may forward to a managed app's `deploy.sh`, consumed by socket validation and deployment orchestration without reversing the lib/services dependency. || `apiContractSchemas.js` | Canonical Zod request contracts for externally callable APIs plus `zodToOpenApiSchema` (plain JSON Schema — the 3.0.3 conversion happens at the OpenAPI document boundary, not here); runtime routes and OpenAPI use the same schema objects. |+| `codeAnimationPackage.js` | Versioned data-only Code Animation package schema, byte/path/reference integrity limits, SHA-256 revision binding, `createCodeAnimationPackage` and `summarizeCodeAnimationPackage`; validation never executes or stages code. || `socketEventContracts.js` | Payload contracts for modeled Socket.IO events, reusing live Zod validation for inbound events and documenting public outbound snapshots. || `socketEventInventory.js` | Cached source-derived Socket.IO event inventory: event names and directions only, with no checked-in manifest or positional source metadata. || `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, result + approximate-token bounds, source-freshness status, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. |diff --git a/server/lib/codeAnimationPackage.js b/server/lib/codeAnimationPackage.jsnew file mode 100644index 0000000000..f9e1f61056--- /dev/null+++ b/server/lib/codeAnimationPackage.js@@ -0,0 +1,161 @@+/** Data-only portable project boundary. Validation never reads or executes files. */+import { createHash } from 'crypto';+import { z } from 'zod';+import { canonicalStringify } from './objects.js';+import { EFFORT_LEVELS } from './providerModels.js';++export const CODE_ANIMATION_PACKAGE_LIMITS = Object.freeze({+ files: 64,+ fileBytes: 2 * 1024 * 1024,+ totalBytes: 8 * 1024 * 1024,+ pathLength: 240,+});++const L = CODE_ANIMATION_PACKAGE_LIMITS;+const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');+const hashSchema = z.string().regex(/^[a-f0-9]{64}$/, 'Expected a SHA-256 digest');+// Portable paths have one spelling on Windows and POSIX. No escaping/decoding+// is performed by the package contract, and hidden/config paths are excluded.+const pathSchema = z.string().min(1).max(L.pathLength).refine((value) =>+ value.split('/').every((part) => /^[a-z0-9](?:[a-z0-9._-]*[a-z0-9_-])?$/i.test(part)+ && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)),+'Expected a portable relative package path');+const text = (max) => z.string().max(max);+const settingsSchema = z.object({+ harness: text(128).nullable(),+ connection: text(128).nullable(),+ mode: z.enum(['api', 'cli', 'tui']).nullable(),+ model: text(256).nullable(),+ effort: z.enum(EFFORT_LEVELS).nullable(),+}).strict();++const manifestSchema = z.object({+ title: text(200),+ brief: z.object({ concept: text(6000), cast: text(4000), onScreenText: text(4000) }).strict(),+ styleGuide: text(16000),+ renderer: z.object({+ kind: z.enum(['browser', 'blender']),+ version: z.string().min(1).max(128),+ engine: text(128).nullable(),+ }).strict(),+ format: z.object({+ width: z.number().int().min(2).max(8192).multipleOf(2),+ height: z.number().int().min(2).max(8192).multipleOf(2),+ fps: z.number().int().min(1).max(60),+ durationSeconds: z.number().positive().max(180),+ }).strict(),+ seed: z.number().int().min(0).max(0xffffffff).nullable(),+ entrypoints: z.array(z.object({+ role: z.enum(['scene', 'preview', 'render']), path: pathSchema,+ }).strict()).min(1).max(3),+ assets: z.array(pathSchema).max(L.files),+ shots: z.array(z.object({+ label: text(200), startSeconds: z.number().nonnegative(), endSeconds: z.number().positive(),+ }).strict()).max(128),+ events: z.array(z.object({ label: text(200), atSeconds: z.number().nonnegative() }).strict()).max(512),+ audio: z.discriminatedUnion('kind', [+ z.object({ kind: z.literal('silence') }).strict(),+ z.object({ kind: z.literal('procedural'), notes: text(1500) }).strict(),+ // External audio is a declaration only: it contains no install-local URL/id.+ z.object({ kind: z.literal('external'), notes: text(1500) }).strict(),+ z.object({ kind: z.literal('file'), path: pathSchema }).strict(),+ ]),+ execution: z.object({ requested: settingsSchema.nullable(), effective: settingsSchema.nullable() }).strict(),+}).strict();++const fileSchema = z.object({+ path: pathSchema,+ encoding: z.enum(['utf8', 'base64']),+ content: z.string().max(4 * Math.ceil(L.fileBytes / 3)),+ sha256: hashSchema,+}).strict();++// Hash decoded bytes through file digests, not base64/UTF-8 transport spelling.+// File order is incidental; shot/event/entrypoint order remains semantic.+const revisionHashOf = ({ schemaVersion, manifest, files }) => digest(canonicalStringify({+ schemaVersion,+ manifest,+ files: files.map(({ path, sha256 }) => ({ path, sha256 })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0),+}));++const shapeSchema = z.object({+ schemaVersion: z.literal(1),+ manifest: manifestSchema,+ files: z.array(fileSchema).min(1).max(L.files),+ revisionHash: hashSchema,+}).strict();++export const codeAnimationPackageSchema = shapeSchema.superRefine((pkg, ctx) => {+ const issue = (path, message) => ctx.addIssue({ code: 'custom', path, message });+ const paths = new Set();+ const folded = new Set();+ let totalBytes = 0;+ for (const [index, file] of pkg.files.entries()) {+ const lower = file.path.toLowerCase();+ if (folded.has(lower)) issue(['files', index, 'path'], 'Duplicate or case-colliding file path');+ folded.add(lower);+ paths.add(file.path);+ // Bound allocation before decoding, even when a child string is already invalid.+ if (file.content.length > 4 * Math.ceil(L.fileBytes / 3)) continue;+ const bytes = Buffer.from(file.content, file.encoding === 'base64' ? 'base64' : 'utf8');+ if (bytes.toString(file.encoding === 'base64' ? 'base64' : 'utf8') !== file.content) {+ issue(['files', index, 'content'], 'Noncanonical base64 or invalid UTF-8 text');+ }+ totalBytes += bytes.length;+ if (bytes.length > L.fileBytes) issue(['files', index, 'content'], 'File exceeds the decoded byte limit');+ if (digest(bytes) !== file.sha256) issue(['files', index, 'sha256'], 'File digest does not match its bytes');+ }+ if (totalBytes > L.totalBytes) issue(['files'], 'Package exceeds the decoded byte limit');+ for (const [index, file] of pkg.files.entries()) {+ const parts = file.path.toLowerCase().split('/');+ if (parts.slice(0, -1).some((_, i) => folded.has(parts.slice(0, i + 1).join('/')))) {+ issue(['files', index, 'path'], 'File path collides with a parent file');+ }+ }+ const roles = new Set();+ for (const [index, entry] of pkg.manifest.entrypoints.entries()) {+ if (roles.has(entry.role)) issue(['manifest', 'entrypoints', index, 'role'], 'Duplicate entrypoint role');+ roles.add(entry.role);+ if (!paths.has(entry.path)) issue(['manifest', 'entrypoints', index, 'path'], 'Entrypoint file is missing');+ }+ for (const [index, path] of pkg.manifest.assets.entries()) {+ if (!paths.has(path)) issue(['manifest', 'assets', index], 'Asset file is missing');+ }+ if (pkg.manifest.audio.kind === 'file' && !paths.has(pkg.manifest.audio.path)) {+ issue(['manifest', 'audio', 'path'], 'Audio file is missing');+ }+ const duration = pkg.manifest.format.durationSeconds;+ for (const [index, shot] of pkg.manifest.shots.entries()) {+ if (shot.endSeconds <= shot.startSeconds || shot.endSeconds > duration) {+ issue(['manifest', 'shots', index], 'Shot must have positive length within the film');+ }+ }+ for (const [index, event] of pkg.manifest.events.entries()) {+ if (event.atSeconds > duration) issue(['manifest', 'events', index], 'Event lies outside the film');+ }+ if (revisionHashOf(pkg) !== pkg.revisionHash) issue(['revisionHash'], 'Revision digest does not match the package');+});++/** Build a package from explicit metadata and text/binary file bytes. */+export function createCodeAnimationPackage(manifest, files) {+ const payload = {+ schemaVersion: 1,+ manifest,+ files: files.map(({ path, content, encoding = 'utf8' }) => ({+ path, content, encoding, sha256: digest(Buffer.from(content, encoding === 'base64' ? 'base64' : 'utf8')),+ })),+ };+ return codeAnimationPackageSchema.parse({ ...payload, revisionHash: revisionHashOf(payload) });+}++/** Integrity is a data check, never a verdict on code safety or render quality. */+export function summarizeCodeAnimationPackage(pkg) {+ return {+ schemaVersion: pkg.schemaVersion,+ revisionHash: pkg.revisionHash,+ renderer: pkg.manifest.renderer,+ fileCount: pkg.files.length,+ totalBytes: pkg.files.reduce((sum, file) => sum + Buffer.byteLength(file.content, file.encoding === 'base64' ? 'base64' : 'utf8'), 0),+ executed: false,+ };+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 10ed9643fd..b747f544bc 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -19,6 +19,7 @@export * from './appPromptPlaceholders.js';export * from './appDeployFlags.js';export * from './apiContractSchemas.js';+export * from './codeAnimationPackage.js';export * from './autonomousJobTask.js';export * from './asyncApiSpec.js';export * from './avatarVariants.js';diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex ecbc654c65..80c4f5f7da 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -9,6 +9,8 @@* GET /api/code-animation/jobs list saved jobs for the gallery* GET /api/code-animation/generate/:id poll a job (html once completed)* POST /api/code-animation/:id/export queue a frame-exact MP4 render → 202 media job+ * GET /api/code-animation/:id/package download a portable source package+ * POST /api/code-animation/packages/validate check package data/integrity only*/import { Router } from 'express';@@ -27,6 +29,8 @@ import {startCodeAnimationGeneration,} from '../services/codeAnimation/index.js';import { startCodeAnimationExport } from '../services/codeAnimation/export.js';+import { exportCodeAnimationPackage } from '../services/codeAnimation/package.js';+import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../lib/codeAnimationPackage.js';import {CODE_ANIMATION_ASPECT_RATIOS,CODE_ANIMATION_LIMITS,@@ -158,6 +162,21 @@ router.get('/generate/:id', asyncHandler(async (req, res) => {const exportParamsSchema = z.object({ id: z.string().uuid() }).strict();+// External harness handoff is data-only. Validation grants no execution and+// neither stages imported files nor changes a saved/accepted animation.+router.post('/packages/validate', (req, res) => {+ const pkg = validateRequest(codeAnimationPackageSchema, req.body);+ res.json(summarizeCodeAnimationPackage(pkg));+});++router.get('/:id/package', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ const pkg = await exportCodeAnimationPackage(id);+ res.attachment(`code-animation-${id}.json`);+ res.set('X-Content-Type-Options', 'nosniff');+ res.json(pkg);+}));+// Frame-exact export: the stored HTML renders through the HTML-composition// pipeline (seek each frame, H.264 MP4, Media History) on the media queue.// Progress streams from /api/html-composition/:jobId/events.diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex 9f31980527..ec84e3c8f1 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -4,6 +4,10 @@ import { mkdirSync, writeFileSync } from 'fs';import { join } from 'path';import { request } from '../lib/testHelper.js';import { errorMiddleware, ServerError } from '../lib/errorHandler.js';+import { createHash } from 'crypto';+import { canonicalStringify } from '../lib/objects.js';+import { createCodeAnimationPackage, CODE_ANIMATION_PACKAGE_LIMITS } from '../lib/codeAnimationPackage.js';+import { JSON_BODY_LIMIT } from '../lib/uploadLimits.js';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';const { codeAnimationRecords, codeAnimationHtml } = vi.hoisted(() => ({@@ -54,13 +58,13 @@ import { getUniverse } from '../services/universeBuilder/crud.js';import { getBoard } from '../services/moodBoard/db.js';import { getProviderById } from '../services/providers.js';import { getTrack } from '../services/tracks/index.js';-import { listCodeAnimationJobPage, listCodeAnimationJobRecords } from '../services/codeAnimation/jobStore.js';+import { listCodeAnimationJobPage, listCodeAnimationJobRecords, readCodeAnimationHtml, saveCodeAnimationHtml, saveCodeAnimationJobRecord } from '../services/codeAnimation/jobStore.js';import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../services/promptRunner.js';import routes from './codeAnimation.js';const makeApp = () => {const app = express();- app.use(express.json());+ app.use(express.json({ limit: JSON_BODY_LIMIT }));app.use('/api/code-animation', routes);app.use(errorMiddleware);return app;@@ -115,6 +119,159 @@ beforeEach(() => {resolveProviderAndModel.mockResolvedValue({ provider: { id: 'api-1', type: 'api' }, selectedModel: 'example-model' });});+describe('Code Animation portable packages', () => {+ const id = '00000000-0000-4000-8000-000000000001';+ const html = '<!doctype html><html><body><script>window.renderFrame = t => t;</script></body></html>\n';+ const savedJob = () => ({+ id, status: 'completed', title: 'Example animation', providerId: 'local-provider',+ model: 'example-model', runId: 'local-run',+ frame: { width: 1920, height: 1080, fps: 24, durationSeconds: 15 },+ input: { concept: 'A brass toy takes flight', cast: 'A mechanical beetle', onScreenText: 'Takeoff',+ styleNotes: 'Painted surfaces', renderer: 'webgl', soundtrack: 'none', universeId: 'local-universe' },+ prompt: 'Example local path: <local-path>', attachments: [{ url: '/api/uploads/example.png' }],+ });+ const pkg = () => createCodeAnimationPackage({+ title: 'Example short', brief: { concept: 'A toy takes flight', cast: '', onScreenText: '' },+ styleGuide: '', renderer: { kind: 'blender', version: 'example-runtime-v1', engine: 'EEVEE' },+ format: { width: 1920, height: 1080, fps: 24, durationSeconds: 15 }, seed: 42,+ entrypoints: [{ role: 'scene', path: 'src/scene.py' }], assets: ['assets/sound.wav'],+ shots: [{ label: 'Reveal', startSeconds: 0, endSeconds: 15 }],+ events: [{ label: 'Impact', atSeconds: 3 }], audio: { kind: 'file', path: 'assets/sound.wav' },+ execution: { requested: null, effective: null },+ }, [{ path: 'src/scene.py', content: 'raise RuntimeError("must never execute")\n' },+ { path: 'assets/sound.wav', content: Buffer.from([0, 255, 128]).toString('base64'), encoding: 'base64' }]);+ // Simulate an external harness minting hashes, including for invalid paths or+ // sizes, so rejection proves the declared boundary rather than a stale hash.+ const rehash = (value) => {+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');+ value.files.forEach((file) => { file.sha256 = sha(Buffer.from(file.content, file.encoding === 'base64' ? 'base64' : 'utf8')); });+ value.revisionHash = sha(canonicalStringify({ schemaVersion: value.schemaVersion, manifest: value.manifest,+ files: value.files.map(({ path, sha256 }) => ({ path, sha256 })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0) }));+ return value;+ };+ const validate = (value) => request(makeApp()).post('/api/code-animation/packages/validate').send(value);++ it('downloads exact legacy HTML with portable fields, validates it, and still reopens the job', async () => {+ codeAnimationRecords.set(id, savedJob());+ codeAnimationHtml.set(id, html);+ const app = makeApp();+ const response = await request(app).get(`/api/code-animation/${id}/package`);+ expect(response.status).toBe(200);+ expect(response.headers['content-disposition']).toContain(`code-animation-${id}.json`);+ expect(response.headers['x-content-type-options']).toBe('nosniff');+ expect(response.body.files).toEqual([{ path: 'index.html', encoding: 'utf8', content: html,+ sha256: createHash('sha256').update(html).digest('hex') }]);+ expect(response.body.manifest).toMatchObject({ title: 'Example animation', styleGuide: 'Painted surfaces',+ brief: { concept: 'A brass toy takes flight', cast: 'A mechanical beetle', onScreenText: 'Takeoff' },+ format: savedJob().frame, execution: { requested: null, effective: null }, seed: null });+ expect(JSON.stringify(response.body)).not.toMatch(/local-provider|local-run|local-universe|local-path|api\/uploads/);+ const checked = await validate(response.body);+ expect(checked.status).toBe(200);+ expect(checked.body).toMatchObject({ revisionHash: response.body.revisionHash, fileCount: 1, executed: false });+ expect((await request(app).get(`/api/code-animation/generate/${id}`)).body.html).toBe(html);+ });++ it('validates Blender/binary packages without reading, writing, generating, or executing work', async () => {+ const value = pkg();+ const checked = await validate(value);+ expect(checked.status).toBe(200);+ expect(checked.body).toEqual({ schemaVersion: 1, revisionHash: value.revisionHash,+ renderer: value.manifest.renderer, fileCount: 2, totalBytes: Buffer.byteLength(value.files[0].content) + 3, executed: false });+ expect(readCodeAnimationHtml).not.toHaveBeenCalled();+ expect(saveCodeAnimationHtml).not.toHaveBeenCalled();+ expect(saveCodeAnimationJobRecord).not.toHaveBeenCalled();+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ // Object key/file ordering and equivalent transport encoding are incidental.+ value.manifest.renderer = { engine: 'EEVEE', version: 'example-runtime-v1', kind: 'blender' };+ value.files.reverse();+ value.files[1].content = Buffer.from(value.files[1].content).toString('base64');+ value.files[1].encoding = 'base64';+ expect((await validate(value)).body.revisionHash).toBe(checked.body.revisionHash);+ value.files[1].content = Buffer.from('changed source').toString('base64');+ expect((await validate(value)).status).toBe(400);+ rehash(value);+ const changed = await validate(value);+ expect(changed.status).toBe(200);+ expect(changed.body.revisionHash).not.toBe(checked.body.revisionHash);+ });++ it.each(['../scene.py', '/scene.py', 'C:/scene.py', 'src\\scene.py', 'src//scene.py',+ 'src/./scene.py', 'src/%2e%2e/scene.py', 'src/scene.py.', 'src/CON.py', '.git/config'])+ ('rejects portable path escape/ambiguity: %s', async (path) => {+ const value = pkg();+ value.files[0].path = path;+ value.manifest.entrypoints[0].path = path;+ const response = await validate(rehash(value));+ expect(response.status).toBe(400);+ expect(response.body.context.details.some(({ message }) => message.includes('portable relative package path'))).toBe(true);+ });++ it.each([+ ['unknown version', (v) => { v.schemaVersion = 2; }],+ ['installation command', (v) => { v.manifest.renderer.command = 'example executable'; }],+ ['case collision', (v) => { v.files.push({ ...v.files[0], path: 'SRC/scene.py' }); }],+ ['duplicate path', (v) => { v.files.push({ ...v.files[0] }); }],+ ['file as parent', (v) => { v.files.push({ ...v.files[0], path: 'src/scene.py/child.py' }); }],+ ['missing entrypoint', (v) => { v.manifest.entrypoints[0].path = 'missing.py'; }],+ ['missing asset', (v) => { v.manifest.assets = ['missing.png']; }],+ ['missing audio', (v) => { v.manifest.audio.path = 'missing.wav'; }],+ ['backwards shot', (v) => { v.manifest.shots[0].startSeconds = 16; }],+ ['late event', (v) => { v.manifest.events[0].atSeconds = 16; }],+ ['noncanonical base64', (v) => { v.files[1].content += '!'; }],+ ['invalid UTF-8 text', (v) => { v.files[0].content = '\ud800'; }],+ ])('rejects malformed packages: %s', async (_name, mutate) => {+ const value = pkg();+ mutate(value);+ expect((await validate(rehash(value))).status).toBe(400);+ });++ it('rejects a stale revision digest even when every file digest is correct', async () => {+ const value = pkg();+ value.manifest.seed = 43;+ const response = await validate(value);+ expect(response.status).toBe(400);+ expect(response.body.context.details).toEqual([{ path: 'revisionHash', message: 'Revision digest does not match the package' }]);+ });++ it('enforces decoded per-file, aggregate, and file-count bounds with correct hashes', async () => {+ const value = pkg();+ value.files[0].content = 'é'.repeat(CODE_ANIMATION_PACKAGE_LIMITS.fileBytes / 2 + 1);+ const oversized = await validate(rehash(value));+ expect(oversized.status).toBe(400);+ expect(oversized.body.context.details).toContainEqual({ path: 'files.0.content', message: 'File exceeds the decoded byte limit' });+ value.files = Array.from({ length: 5 }, (_, i) => ({ ...pkg().files[0], path: `file${i}.py`,+ content: 'a'.repeat(CODE_ANIMATION_PACKAGE_LIMITS.fileBytes) }));+ value.manifest.entrypoints[0].path = 'file0.py';+ value.manifest.assets = [];+ value.manifest.audio = { kind: 'silence' };+ const aggregate = await validate(rehash(value));+ expect(aggregate.status).toBe(400);+ expect(aggregate.body.context.details).toContainEqual({ path: 'files', message: 'Package exceeds the decoded byte limit' });+ value.files = Array.from({ length: 65 }, (_, i) => ({ ...pkg().files[0], path: `file${i}.py` }));+ expect((await validate(rehash(value))).status).toBe(400);+ });++ it('reports unavailable jobs and declares external/procedural audio without fetching it', async () => {+ const app = makeApp();+ expect((await request(app).get(`/api/code-animation/${id}/package`)).status).toBe(404);+ expect((await request(app).get('/api/code-animation/not-an-id/package')).status).toBe(400);+ codeAnimationRecords.set(id, { ...savedJob(), status: 'failed' });+ expect((await request(app).get(`/api/code-animation/${id}/package`)).status).toBe(409);+ expect(readCodeAnimationHtml).not.toHaveBeenCalled();+ codeAnimationHtml.set(id, html);+ codeAnimationRecords.set(id, { ...savedJob(), audioUrl: '/api/uploads/example.wav' });+ expect((await request(app).get(`/api/code-animation/${id}/package`)).body.manifest.audio.kind).toBe('external');+ codeAnimationRecords.set(id, { ...savedJob(), input: { ...savedJob().input, soundtrack: 'procedural' } });+ expect((await request(app).get(`/api/code-animation/${id}/package`)).body.manifest.audio.kind).toBe('procedural');+ expect(getTrack).not.toHaveBeenCalled();+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ codeAnimationHtml.set(id, 'a'.repeat(CODE_ANIMATION_PACKAGE_LIMITS.fileBytes + 1));+ const tooLarge = await request(app).get(`/api/code-animation/${id}/package`);+ expect(tooLarge.status).toBe(422);+ expect(tooLarge.body.code).toBe('CODE_ANIMATION_PACKAGE_TOO_LARGE');+ });+});+describe('GET /api/code-animation/jobs', () => {it('reconciles only stale running records before paging and counting', async () => {const id = '00000000-0000-4000-8000-000000000001';diff --git a/server/services/codeAnimation/package.js b/server/services/codeAnimation/package.jsnew file mode 100644index 0000000000..630eb45faf--- /dev/null+++ b/server/services/codeAnimation/package.js@@ -0,0 +1,40 @@+import { ServerError } from '../../lib/errorHandler.js';+import { createCodeAnimationPackage, CODE_ANIMATION_PACKAGE_LIMITS } from '../../lib/codeAnimationPackage.js';+import { getCodeAnimationJobRecord, readCodeAnimationHtml } from './jobStore.js';++/** Export explicit portable fields only; never copy a job record or its prompt. */+export async function exportCodeAnimationPackage(id) {+ const job = await getCodeAnimationJobRecord(id);+ if (!job) throw new ServerError('Generation job not found', { status: 404, code: 'NOT_FOUND' });+ if (job.status !== 'completed') {+ throw new ServerError('Only completed animations have a source package', { status: 409, code: 'CODE_ANIMATION_NOT_COMPLETED' });+ }+ const html = await readCodeAnimationHtml(id);+ if (Buffer.byteLength(html) > CODE_ANIMATION_PACKAGE_LIMITS.fileBytes) {+ throw new ServerError('This source exceeds the package file limit; use Download HTML instead', {+ status: 422, code: 'CODE_ANIMATION_PACKAGE_TOO_LARGE',+ });+ }+ const input = job.input || {};+ return createCodeAnimationPackage({+ title: job.title || '',+ brief: { concept: input.concept || '', cast: input.cast || '', onScreenText: input.onScreenText || '' },+ styleGuide: input.styleNotes || '',+ renderer: { kind: 'browser', version: 'code-animation-html-v1', engine: input.renderer || 'auto' },+ format: {+ width: job.frame?.width, height: job.frame?.height,+ fps: job.frame?.fps, durationSeconds: job.frame?.durationSeconds,+ },+ seed: null,+ entrypoints: [{ role: 'preview', path: 'index.html' }],+ assets: [], shots: [], events: [],+ audio: job.audioUrl || input.audio+ ? { kind: 'external', notes: 'The selected audio is not included in this package.' }+ : input.soundtrack === 'procedural'+ ? { kind: 'procedural', notes: 'Live Web Audio in the HTML; no offline soundtrack is included.' }+ : { kind: 'silence' },+ // Legacy jobs do not capture the full effective harness/connection/mode.+ // Unknown provenance stays null; local provider ids never leave the install.+ execution: { requested: null, effective: null },+ }, [{ path: 'index.html', content: html }]);+}