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: validate launch-video privacy and reading time before rendering (#8649)
[._.]/ Adam Eivy6cd204cad2be
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex fa4074f4bd..0deeeaa3f6 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -63,3 +63,48 @@ The real-browser contract suite ina temporary browser profile and data root, never the live managed browser.Set `CHROME_PATH` when Chrome is not in a standard location. The suite skipsexplicitly when either binary is unavailable; route and queue tests still run.++## Launch-video admission (API foundation)++`POST /api/html-composition/render` accepts `launchVideo: { targetDurationSec: 20 }`.+This option is required for directories rooted at `launch-videos/` and can also+be applied to other composition directories. The app-detail action and CoS+planning task are not part of this API foundation yet (tracked in #8649).++Alongside `index.html`, put non-empty `plan.md`, `caption.txt`, and+`storyboard.json` in the composition directory. A storyboard has this shape:++```json+{+ "posterSec": 5,+ "scenes": [{+ "durationSec": 20,+ "lines": [{+ "text": "Plan your next great project",+ "wordCount": 5,+ "holdSec": 2+ }]+ }]+}+```++Scene durations must total 15–25 seconds, within two seconds of the requested+15–25 second target. Each line's actual whitespace-separated word count must+match `wordCount`; its hold must be at least `max(0.8, 0.3 × words)` seconds and+fit inside the scene. The composition's runtime duration must equal the total.+`posterSec` must be inside that duration and selects the generated thumbnail.++Admission scans all UTF-8 HTML, CSS, JavaScript, JSON, SVG, Markdown, and text+assets, including the plan, storyboard, and caption, for the shared PII patterns+and recognizable secret tokens. It refuses detected values rather than silently+redacting them; errors identify the pattern and file without quoting the value.+Only WOFF/WOFF2 fonts are accepted as binary assets. Raster images, footage, and+other uninspectable formats are refused on this path. Existing general HTML+composition renders retain their asset support.++The same checks run again on the renderer's frozen in-memory assets before any+browser script executes, covering edits while a job waits in the queue. These+are text-pattern and declared-storyboard checks, not proof that arbitrary code+cannot construct private text or violate its declared timing. Producers must+still avoid secrets and live records, use fictional content, and make the+composition faithfully implement the storyboard. Nothing is uploaded or posted.diff --git a/server/lib/README.md b/server/lib/README.mdindex 68e0fc2fdb..e5014615f1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -758,3 +758,5 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `modelComparisonComposite.js` | `buildModelComparisonComposite(observations, inventory)` derives a stable sourced index with calibrated and effort estimates, route-specific price references and explicit research gaps. || `messageLogError.js` | `messageLogError(error)` projects mailbox failures to allowlisted codes and HTTP error status, excluding provider text and credentials. |++| `launchVideoValidation.js` | `validateLaunchVideoAssets` checks frozen launch composition text, storyboard reading time, duration, and poster position before rendering. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 6ba2346eff..cc4ff3c92e 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -740,3 +740,5 @@ export * from './chatgptText.js';export * from './modelComparisonComposite.js';export * from './messageLogError.js';++export * from './launchVideoValidation.js';diff --git a/server/lib/launchVideoValidation.js b/server/lib/launchVideoValidation.jsnew file mode 100644index 0000000000..be68a28546--- /dev/null+++ b/server/lib/launchVideoValidation.js@@ -0,0 +1,57 @@+import { extname } from 'node:path';+import { ServerError } from './errorHandler.js';+import { PII_PATTERNS, redactPii } from './piiRedactionPatterns.js';+import { scrubSecretTokens } from './secretText.js';+import { launchVideoOptionsSchema, launchVideoStoryboardSchema, validateRequest } from './validation.js';++const TEXT_TYPES = new Set(['.html', '.css', '.js', '.json', '.svg', '.md', '.txt']);+const fail = message => { throw new ServerError(message, { status: 400, code: 'LAUNCH_VIDEO_INVALID' }); };+const safeName = name => redactPii(scrubSecretTokens(name));++/** Check the exact in-memory assets the browser will consume, before any script runs. */+export function validateLaunchVideoAssets(assets, options) {+ const { targetDurationSec } = validateRequest(launchVideoOptionsSchema, options);+ const texts = new Map();+ for (const [name, bytes] of assets) {+ const filename = safeName(name);+ if (filename !== name) fail(`Private filename: ${filename}`);+ const type = extname(name).toLowerCase();+ // Font bytes are the sole non-text input. Raster screenshots/video could+ // contain private records that text detectors cannot inspect.+ if (type === '.woff' || type === '.woff2') {+ if (bytes.subarray(0, 4).toString('ascii') !== (type === '.woff' ? 'wOFF' : 'wOF2')) fail(`Invalid font: ${filename}`);+ continue;+ }+ if (!TEXT_TYPES.has(type)) fail(`Unsupported launch-video asset: ${filename}`);+ const text = bytes.toString('utf8');+ if (!Buffer.from(text, 'utf8').equals(bytes) || text.includes('\0')) fail(`Text must be UTF-8: ${filename}`);+ for (const { code, pattern } of PII_PATTERNS) {+ if (pattern.test(text)) fail(`${code} in ${filename}`);+ }+ if (scrubSecretTokens(text) !== text) fail(`secret-token in ${filename}`);+ texts.set(name, text);+ }+ for (const name of ['/index.html', '/plan.md', '/storyboard.json', '/caption.txt']) {+ if (!texts.get(name)?.trim()) fail(`Missing or empty ${name}`);+ }+ // JSON.parse's native message can quote private source text. Keep failures bounded.+ let raw;+ try { raw = JSON.parse(texts.get('/storyboard.json')); } catch { fail('Invalid JSON in /storyboard.json'); }+ const parsed = launchVideoStoryboardSchema.safeParse(raw);+ if (!parsed.success) fail(`Invalid storyboard.json field: ${parsed.error.issues[0].path.join('.')}`);+ const storyboard = parsed.data;+ const durationSec = storyboard.scenes.reduce((sum, scene) => sum + scene.durationSec, 0);+ if (durationSec < 15 || durationSec > 25 || Math.abs(durationSec - targetDurationSec) > 2) {+ fail('storyboard.json scene durations must total 15–25s and match targetDurationSec within 2s');+ }+ if (storyboard.posterSec >= durationSec) fail('storyboard.json posterSec must be inside the video');+ storyboard.scenes.forEach((scene, sceneIndex) => scene.lines.forEach((line, lineIndex) => {+ const label = `storyboard.json scene ${sceneIndex + 1} line ${lineIndex + 1}`;+ const words = line.text.split(/\s+/u).length;+ if (line.wordCount !== words) fail(`${label}: wordCount must match the text`);+ if (line.holdSec < Math.max(0.8, 0.3 * words) || line.holdSec > scene.durationSec) {+ fail(`${label}: holdSec must allow reading time and fit inside its scene`);+ }+ }));+ return { durationSec, posterSec: storyboard.posterSec };+}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 7d0d64741b..9eaeefc769 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2427,8 +2427,25 @@ export const mindBundleApplySchema = z.object({)).strict(),}).strict();+export const launchVideoOptionsSchema = z.object({+ targetDurationSec: z.number().min(15).max(25),+}).strict();++export const launchVideoStoryboardSchema = z.object({+ posterSec: z.number().nonnegative(),+ scenes: z.array(z.object({+ durationSec: z.number().positive(),+ lines: z.array(z.object({+ text: z.string().trim().min(1).max(10000),+ wordCount: z.number().int().positive(),+ holdSec: z.number().positive(),+ }).strict()).max(100),+ }).strict()).min(1).max(100),+}).strict();+// HTML composition inputs are local, editable assets, never provider prompts.export const htmlCompositionRenderSchema = z.object({+ launchVideo: launchVideoOptionsSchema.optional(),directory: z.string().min(1).max(1024).refine(value => !value.startsWith('/') && !value.includes('\\') && !value.includes(':') && !value.split('/').some(part => part === '..' || part === '.' || !part), 'directory must be a relative path inside data'),musicTrack: z.string().min(1).max(255).regex(/^[^/\\]+$/, 'musicTrack must be a Music-library filename').optional(),});diff --git a/server/routes/htmlComposition.js b/server/routes/htmlComposition.jsindex 4371aa367a..b9be8238f5 100644--- a/server/routes/htmlComposition.js+++ b/server/routes/htmlComposition.js@@ -7,6 +7,11 @@ const router = Router();router.post('/render', asyncHandler(async (req, res) => {const params = validateRequest(htmlCompositionRenderSchema, req.body);+ if (params.launchVideo || params.directory.split('/')[0] === 'launch-videos') {+ const { snapshotAssets } = await import('../services/htmlComposition/browser.js');+ const { validateLaunchVideoAssets } = await import('../lib/launchVideoValidation.js');+ validateLaunchVideoAssets(await snapshotAssets(params.directory), params.launchVideo);+ }res.status(202).json(await enqueueJob({ kind: 'html-composition', params }));}));diff --git a/server/routes/htmlComposition.launchVideo.test.js b/server/routes/htmlComposition.launchVideo.test.jsnew file mode 100644index 0000000000..cafa297428--- /dev/null+++ b/server/routes/htmlComposition.launchVideo.test.js@@ -0,0 +1,103 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import express from 'express';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';+import { PATHS } from '../lib/fileUtils.js';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { enqueueJob } from '../services/mediaJobQueue/index.js';+import { cdpRequest } from '../services/browserService.js';+import { renderComposition } from '../services/htmlComposition/index.js';+import router from './htmlComposition.js';++vi.mock('../lib/fileUtils.js', async original => makePathsProxy(await original(), {+ dataRoot: () => lazyTempDataRoot('portos-launch-admission-'),+}));+vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(async () => ({ jobId: 'example-job', status: 'queued' })),+ attachSseClient: vi.fn(), cancelJob: vi.fn(),+}));+vi.mock('../services/browserService.js', () => ({ cdpRequest: vi.fn() }));+const app = express();+app.use(express.json());+app.use('/api/html-composition', router);+app.use(errorMiddleware);+const storyboard = () => ({ posterSec: 5, scenes: [{ durationSec: 20,+ lines: [{ text: 'Plan your next great project', wordCount: 5, holdSec: 2 }],+}] });+let directory;+const put = (name, text) => writeFile(join(PATHS.data, directory, name), text);+const submit = (extra = {}) => request(app).post('/api/html-composition/render').send({+ directory, launchVideo: { targetDurationSec: 20 }, ...extra,+});+beforeEach(async () => {+ vi.clearAllMocks();+ directory = `launch-videos/example/${randomUUID()}`;+ await mkdir(join(PATHS.data, directory), { recursive: true });+ await put('index.html', '<html><body>A fictional product demo</body></html>');+ await put('plan.md', 'Show entry, action, then result with fictional stand-ins.');+ await put('caption.txt', 'Turn a project into a clear plan.');+ await put('storyboard.json', JSON.stringify(storyboard()));+});+afterAll(cleanupTempDataRoots);++describe('launch-video render admission', () => {+ it.each([+ ['index.html', '[email protected]', 'email-address'],+ ['caption.txt', `ghp_${'a'.repeat(25)}`, 'secret-token'],+ ['plan.md', 'host-example.local', 'network-host'],+ ['notes.txt', '192.0.2.10', 'ip-literal'],+ ])('refuses detected private text in %s without echoing it, and accepts correction', async (file, value, code) => {+ await put(file, value);+ const denied = await submit();+ expect(denied.status).toBe(400);+ expect(JSON.stringify(denied.body)).toContain(`${code} in /${file}`);+ expect(JSON.stringify(denied.body)).not.toContain(value);+ expect(enqueueJob).not.toHaveBeenCalled();+ await put(file, 'Fictional product content');+ expect((await submit()).status).toBe(202);+ expect(enqueueJob).toHaveBeenCalledTimes(1);+ });+ it('rejects the five-word 0.9s line and a fabricated word count', async () => {+ const plan = storyboard();+ plan.scenes[0].lines[0].holdSec = 0.9;+ await put('storyboard.json', JSON.stringify(plan));+ const denied = await submit();+ expect(denied.status).toBe(400);+ expect(JSON.stringify(denied.body)).toContain('scene 1 line 1');+ plan.scenes[0].lines[0].wordCount = 1;+ await put('storyboard.json', JSON.stringify(plan));+ expect(JSON.stringify((await submit()).body)).toContain('wordCount');+ expect(enqueueJob).not.toHaveBeenCalled();+ });+ it.each([+ plan => { plan.scenes[0].durationSec = 14; },+ plan => { plan.scenes[0].durationSec = 23; },+ plan => { plan.posterSec = 20; },+ plan => { plan.scenes[0].lines[0].holdSec = 21; },+ ])('refuses invalid timeline bounds', async change => {+ const plan = storyboard();+ change(plan);+ await put('storyboard.json', JSON.stringify(plan));+ expect((await submit()).status).toBe(400);+ expect(enqueueJob).not.toHaveBeenCalled();+ });+ it('cannot omit the gate for a launch-videos directory', async () => {+ expect((await submit({ launchVideo: undefined })).status).toBe(400);+ expect(enqueueJob).not.toHaveBeenCalled();+ });+ it('fails closed on uninspectable raster assets', async () => {+ await put('screen.png', Buffer.from([0, 1, 2]));+ expect((await submit()).status).toBe(400);+ expect(enqueueJob).not.toHaveBeenCalled();+ });+ it('rechecks files changed after admission before opening the browser', async () => {+ expect((await submit()).status).toBe(202);+ const { params } = enqueueJob.mock.calls[0][0];+ await put('caption.txt', '[email protected]');+ await expect(renderComposition({ ...params, jobId: randomUUID() })).rejects.toThrow('email-address in /caption.txt');+ expect(cdpRequest).not.toHaveBeenCalled();+ });+});diff --git a/server/services/htmlComposition/browser.js b/server/services/htmlComposition/browser.jsindex 1ad2e5aa55..9187bfeae5 100644--- a/server/services/htmlComposition/browser.js+++ b/server/services/htmlComposition/browser.js@@ -17,7 +17,7 @@ function inside(root, path) {// Freeze the input before any script runs. Symlinks are refused, including// symlinked assets, so the virtual origin cannot export another data store.-async function snapshotAssets(directory) {+export async function snapshotAssets(directory) {const root = await realpath(PATHS.data);const dir = await realpath(resolve(root, directory));if (!inside(root, dir)) throw new Error('directory must be inside data');@@ -45,8 +45,9 @@ async function snapshotAssets(directory) {// One browser-level socket owns a disposable context and its hidden target.// Disconnect/abort rejects pending commands; disposeOnDetach covers crashes.-export async function openComposition(directory, { signal } = {}) {+export async function openComposition(directory, { signal, validateAssets } = {}) {const assets = await snapshotAssets(directory);+ validateAssets?.(assets);signal?.throwIfAborted();const response = await cdpRequest('/json/version');if (!response.ok) throw new Error('Managed browser is unavailable');diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.jsindex 6dcdcf3427..aed2a898d0 100644--- a/server/services/htmlComposition/index.js+++ b/server/services/htmlComposition/index.js@@ -7,6 +7,7 @@ import { mutateVideoHistory } from '../videoGen/history.js';import { resolveMusicTrackPath } from '../pipeline/audioMux.js';import { openComposition } from './browser.js';import { encodeComposition } from './encode.js';+import { validateLaunchVideoAssets } from '../../lib/launchVideoValidation.js';const active = new Map();@@ -28,11 +29,15 @@ export async function renderComposition({ jobId, ...input }) {let result;let failure;try {- const { directory, musicTrack } = validateRequest(htmlCompositionRenderSchema, input);+ const { directory, musicTrack, launchVideo } = validateRequest(htmlCompositionRenderSchema, input);const musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;if (musicTrack && !musicPath) throw new Error('musicTrack is missing from the Music library');signal.throwIfAborted();- page = await openComposition(directory, { signal });+ let launchPlan;+ const needsLaunchGate = launchVideo || directory.split('/')[0] === 'launch-videos';+ page = await openComposition(directory, { signal, validateAssets: needsLaunchGate+ ? assets => { launchPlan = validateLaunchVideoAssets(assets, launchVideo); }+ : undefined });const metadata = await page.evaluate(`(() => {const c = globalThis.portosComposition;if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');@@ -41,6 +46,9 @@ export async function renderComposition({ jobId, ...input }) {const parsed = htmlCompositionContractSchema.safeParse(metadata);if (!parsed.success) throw new Error(parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '));const contract = parsed.data;+ if (launchPlan && Math.abs(contract.durationSec - launchPlan.durationSec) > 1e-8) {+ throw new Error('Composition durationSec must match storyboard.json');+ }await ensureDir(PATHS.videos);await encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress: progress => {videoGenEvents.emit('progress', { generationId: jobId, progress: progress * 0.95 });@@ -50,7 +58,7 @@ export async function renderComposition({ jobId, ...input }) {await page.close({ verify: true });page = null;signal.throwIfAborted();- const thumbnail = await generateThumbnail(outputPath, jobId);+ const thumbnail = await generateThumbnail(outputPath, jobId, launchPlan ? { atSec: launchPlan.posterSec } : undefined);if (!thumbnail) throw new Error('Composition thumbnail generation failed');signal.throwIfAborted();// Once the shared history write starts, cancellation must be refused.diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.jsindex f3c58eb82b..3048cf204d 100644--- a/server/services/htmlComposition/index.test.js+++ b/server/services/htmlComposition/index.test.js@@ -103,6 +103,24 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpeexpect((await readFile(join(PATHS.videoThumbnails, result.thumbnail))).length).toBeGreaterThan(0);}, 30000);+ it('renders a gated launch composition and uses its declared poster beat', async () => {+ const html = `<!doctype html><html><body><script>+ globalThis.portosComposition = { durationSec:15, fps:12, width:1280, height:720,+ async seek(t) { document.body.style.background = t >= 10 ? 'rgb(255,0,0)' : 'rgb(0,0,255)'; }+ };</script></body></html>`;+ const input = await composition(html);+ await writeFile(join(PATHS.data, input.directory, 'plan.md'), 'A fictional product demonstration.');+ await writeFile(join(PATHS.data, input.directory, 'caption.txt'), 'Make a clear plan.');+ await writeFile(join(PATHS.data, input.directory, 'storyboard.json'), JSON.stringify({+ posterSec: 11, scenes: [{ durationSec: 15, lines: [] }],+ }));+ const result = await renderComposition({ ...input, launchVideo: { targetDurationSec: 15 } });+ const pixel = execFileSync(ffmpeg, ['-v', 'error', '-i', join(PATHS.videoThumbnails, result.thumbnail),+ '-vf', 'scale=1:1', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-']);+ expect(pixel[0]).toBeGreaterThan(220);+ expect(pixel[2]).toBeLessThan(30);+ }, 60000);+it('refuses a remote request by its full URL and removes partial artifacts', async () => {const url = 'https://example.com/forbidden.png';const input = await composition(fixture(`new Image().src = '${url}';`));