← Files Flows by plugin.spaceARCHIVED FILE

scripts/serve.mjs

18.8 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

#!/usr/bin/env node
import { launcherCommand } from '../lib/node-runtime.mjs';
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
import { readFile, realpath, stat } from 'node:fs/promises';
import { dirname, extname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { isEntrypoint } from '../lib/entrypoint.mjs';
import { createLibrary, inferApplication, inferProjectRoot } from '../lib/library.mjs';
import { applicationWithIcon } from '../lib/project-icon.mjs';
import { codexPluginId } from '../lib/codex-handoff.mjs';
import { createCloudProxy } from '../lib/cloud-proxy.mjs';
import { commentAction, createCommentsStore } from '../lib/comments.mjs';
import { readDocument } from '../lib/document.mjs';
import { updateDocument } from '../lib/write-document.mjs';
import { withTestScenarios } from '../lib/test-scenarios.mjs';
import { cloudDocument } from '../lib/cloud-document.mjs';
import { validateCaptureSettings } from '../lib/capture-settings.mjs';

const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf' };
const isInside = (root, path) => { const part = relative(root, path); return part !== '' && !part.startsWith('..') && !isAbsolute(part); };
function json(response, status, value) {
  response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
  response.end(JSON.stringify(value));
}

export function createFlowServer({ file, viewerRoot = resolve(pluginRoot, 'viewer'), libraryRoot, project, appName, cloudUrl = process.env.FLOWS_CLOUD_URL ?? 'https://plugin.space', cloudFetcher }) {
  const initialPath = resolve(file);
  const library = createLibrary(libraryRoot, { origin: cloudUrl });
  const comments = createCommentsStore(libraryRoot);
  const cloud = createCloudProxy(cloudUrl, cloudFetcher, library.access);
  const ready = (async () => { const application = await inferApplication(initialPath, project, appName); const id = await library.register(initialPath, application); await library.discover(initialPath, application); return id; })();
  ready.catch(() => {});
  return createServer(async (request, response) => {
    response.setHeader('X-Content-Type-Options', 'nosniff');
    response.setHeader('Referrer-Policy', 'no-referrer');
    response.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; object-src 'none'");
    const port = response.socket.localPort;
    const allowedHosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
    // A browser keeps cross-site metadata through the login redirect chain.
    // The callback validates state/PKCE; its final page is static and reads no
    // account or local data. All APIs and Host validation keep their usual checks.
    const authReturnPath = new URL(request.url ?? '/', 'http://localhost').pathname;
    const authReturn = request.method === 'GET' && ['/api/auth/callback', '/auth/connected'].includes(authReturnPath);
    if (!allowedHosts.has(request.headers.host) || (!authReturn && ((request.headers.origin && ![...allowedHosts].some(host => request.headers.origin === `http://${host}`)) || request.headers['sec-fetch-site'] === 'cross-site'))) {
      json(response, 403, { error: 'This viewer only accepts requests from its local origin.' }); return;
    }
    try {
      const url = new URL(request.url ?? '/', 'http://localhost');
      const pathname = url.pathname;
      if (pathname === '/api/cloud-config') { json(response, 200, { enabled: Boolean(cloud.origin), origin: cloud.origin, hosted: false, ...(cloud.origin ? { infoUrl: `${cloud.origin}/plugin-access` } : {}) }); return; }
      if (pathname.startsWith('/api/cloud/') || pathname.startsWith('/api/auth/')) { await cloud.handle(request, response); return; }
      if (pathname === '/auth/connected' && request.method === 'GET') {
        const page = await readFile(resolve(pluginRoot, 'assets/auth-connected.html'));
        response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
        response.end(page); return;
      }
      if (pathname === '/auth/connected.js' && request.method === 'GET') {
        const script = await readFile(resolve(pluginRoot, 'assets/auth-connected.js'));
        response.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
        response.end(script); return;
      }
      await ready;
      if (pathname === '/api/capture-preferences') {
        if (request.method === 'GET') { json(response, 200, await library.capturePreferences.read()); return; }
        if (request.method !== 'POST') { json(response, 405, { error: 'Method not supported.' }); return; }
        if (!request.headers['content-type']?.startsWith('application/json')) { json(response, 415, { error: 'Send JSON screenshot preferences.' }); return; }
        let body = '';
        for await (const chunk of request) { body += chunk; if (Buffer.byteLength(body) > 32768) { json(response, 413, { error: 'Settings exceed 32 KB.' }); return; } }
        const { settings, revision } = JSON.parse(body);
        json(response, 200, await library.capturePreferences.save(settings, revision)); return;
      }
      if (pathname === '/api/library/slots' && request.method === 'GET') { json(response, 200, await library.slots()); return; }
      if (pathname === '/api/library' && request.method === 'GET') { const initial = await library.resolve(await ready); await library.discover(initial.path, initial.application); json(response, 200, { flows: await library.list(), access: await library.status(), currentId: await ready }); return; }
      if (pathname === '/api/library/active' && request.method === 'POST') {
        if (!request.headers['content-type']?.startsWith('application/json')) { json(response, 415, { error: 'Send JSON.' }); return; }
        let body = '';
        for await (const chunk of request) { body += chunk; if (Buffer.byteLength(body) > 1024) { json(response, 413, { error: 'Selection exceeds 1 KB.' }); return; } }
        const value = JSON.parse(body);
        json(response, 200, await library.setActive(value?.id, value?.active)); return;
      }
      if (pathname === '/api/new-flow-context' && request.method === 'GET') {
        await library.assertCapacity();
        const flowId = url.searchParams.get('flow');
        const selected = flowId ? await library.resolve(flowId) : undefined;
        const initial = await library.resolve(await ready);
        const projectPath = selected ? await inferProjectRoot(selected.path, dirname(selected.path) === dirname(initial.path) ? project : undefined) : undefined;
        json(response, 200, { pluginId: await codexPluginId(pluginRoot), projectPath }); return;
      }
      const localId = url.searchParams.get('flow');
      const entry = await library.resolve(localId || await ready);
      const documentPath = entry.path;
      if (entry.readOnly && (pathname.startsWith('/api/') || pathname.startsWith('/screens/'))) { json(response, 403, { error: 'This flow is archived. Restore it from your library when a slot is available before opening it.' }); return; }
      if (pathname === '/api/snapshot-settings') {
        if (request.method === 'GET') { json(response, 200, { autoSync: entry.autoSync === true, autoSyncAccount: entry.autoSyncAccount }); return; }
        if (request.method !== 'POST') { json(response, 405, { error: 'Method not supported.' }); return; }
        if (!request.headers['content-type']?.startsWith('application/json')) { json(response, 415, { error: 'Send JSON snapshot settings.' }); return; }
        try {
          let body = '';
          for await (const chunk of request) { body += chunk; if (Buffer.byteLength(body) > 1024) { json(response, 413, { error: 'Snapshot settings exceed 1 KB.' }); return; } }
          const value = JSON.parse(body);
          json(response, 200, await library.setAutoSync(entry.id, value?.autoSync, value?.autoSyncAccount, value?.autoSyncCloudId, value?.preferenceMode));
        } catch (error) { json(response, error.status || 400, { error: error.message }); }
        return;
      }
      if (pathname === '/api/comments') {
        if (request.method === 'GET') { json(response, 200, { comments: (await comments.list(entry.id)).map(comment => ({ ...comment, canManage: !entry.readOnly })), readOnly: entry.readOnly }); return; }
        if (!['POST', 'DELETE'].includes(request.method)) { json(response, 405, { error: 'Method not supported.' }); return; }
        try {
          if (!request.headers['content-type']?.startsWith('application/json')) { json(response, 415, { error: 'Send JSON.' }); return; }
          let content = ''; for await (const chunk of request) { content += chunk; if (Buffer.byteLength(content) > 32768) { json(response, 413, { error: 'Comment request exceeds 32 KB.' }); return; } }
          const value = JSON.parse(content);
          let result;
          result = await library.withWritable(entry.id, async () => {
            if (request.method === 'DELETE') return comments.remove(entry.id, value?.id);
            if (commentAction(value).action === 'resolve') return comments.resolve(entry.id, value);
            return comments.create(entry.id, value, (await readDocument(documentPath)).document);
          });
          json(response, 200, result);
        } catch (error) { json(response, error.status || 400, { error: error.message }); }
        return;
      }
      if (pathname === '/api/bundle' && request.method === 'GET') {
        const { document: localDocument, revision } = await readDocument(documentPath);
        const document = cloudDocument(localDocument);
        // The viewer fetches sources one at a time and optimizes them locally.
        // Do not apply the cloud's encoded bundle limit to these source files.
        const manifest = url.searchParams.get('assets') === 'manifest';
        const assets = {};
        const sourceRevisions = [];
        const root = await realpath(dirname(documentPath));
        const paths = new Map();
        for (const node of document.nodes) {
          if (node.screenshot) paths.set(node.screenshot, { node: node.id });
          for (const [profile, shot] of Object.entries(node.screenshots || {})) paths.set(shot.path, { node: node.id, profile });
        }
        for (const [path, source] of paths) {
          const absolute = await realpath(resolve(root, path));
          if (!isInside(root, absolute) || !['.png', '.jpg', '.jpeg', '.webp', '.gif'].includes(extname(absolute).toLowerCase())) { json(response, 422, { error: 'A screenshot is outside the flow directory or has an unsupported format.' }); return; }
          const { size, mtimeMs, ctimeMs } = await stat(absolute);
          sourceRevisions.push([path, size, mtimeMs, ctimeMs]);
          if (manifest) {
            if (size > 8 * 1024 * 1024) { json(response, 413, { error: 'A source screenshot exceeds the viewer’s 8 MB image limit.' }); return; }
            const query = new URLSearchParams({ flow: entry.id, revision });
            if (source.profile) query.set('profile', source.profile);
            assets[path] = { type: types[extname(absolute).toLowerCase()], size, url: `/screens/${encodeURIComponent(source.node)}?${query}` };
            continue;
          }
          if (size > 3 * 1024 * 1024) { json(response, 413, { error: 'This snapshot needs image optimization. Reopen it in the latest Flows viewer and save again.' }); return; }
          assets[path] = { type: types[extname(absolute).toLowerCase()], data: (await readFile(absolute)).toString('base64') };
          if (Buffer.byteLength(JSON.stringify({ document, assets })) > 4 * 1024 * 1024 - 4096) { json(response, 413, { error: 'This snapshot needs image optimization. Reopen it in the latest Flows viewer and save again.' }); return; }
        }
        const bundle = { document: { ...document, application: await applicationWithIcon(document.application || entry.application, await inferProjectRoot(entry.path, project)) }, assets };
        const sourceRevision = createHash('sha256').update(JSON.stringify([revision, bundle.document.application, sourceRevisions])).digest('hex').slice(0, 16);
        json(response, 200, { ...bundle, revision, sourceRevision, autoSync: !entry.readOnly && entry.autoSync === true, autoSyncAccount: entry.autoSyncAccount, autoSyncCloudId: entry.autoSyncCloudId, readOnly: entry.readOnly }); return;
      }
      if (request.method === 'POST' && pathname === '/api/capture-settings') {
        if (request.headers['content-type'] !== 'application/json') { json(response, 415, { error: 'Send JSON capture settings.' }); return; }
        try {
          let body = '';
          for await (const chunk of request) { body += chunk; if (Buffer.byteLength(body) > 32768) { json(response, 413, { error: 'Settings exceed 32 KB.' }); return; } }
          const { settings, revision } = JSON.parse(body);
          const errors = validateCaptureSettings(settings);
          if (errors.length) { json(response, 422, { error: errors.join('\n') }); return; }
          const result = await library.withWritable(entry.id, () => updateDocument(documentPath, revision, document => ({ ...document, captureSettings: settings })));
          json(response, 200, result);
        } catch (error) { json(response, error.status ?? 400, { error: error.message }); }
        return;
      }
      if (request.method !== 'GET' && request.method !== 'HEAD') { json(response, 405, { error: 'Only capture settings can be edited here. Edit the flow through Codex.' }); return; }
      if (pathname === '/api/flow' || pathname === '/api/export') {
        try {
          const { document, revision } = await readDocument(documentPath);
          if (pathname === '/api/export') {
            response.writeHead(200, {
              'Content-Type': 'application/json; charset=utf-8',
              'Content-Disposition': `attachment; filename="${document.id}.flows.json"`,
              'Cache-Control': 'no-store',
            });
            response.end(request.method === 'HEAD' ? undefined : `${JSON.stringify(withTestScenarios(document), null, 2)}\n`);
          } else json(response, 200, { document, revision, readOnly: entry.readOnly });
        } catch (error) { json(response, 422, { error: error.code === 'ENOENT' ? 'The flow document could not be found.' : error.message }); }
        return;
      }
      let requestedPath;
      let assetRoot;
      if (pathname.startsWith('/screens/')) {
        const { document, revision } = await readDocument(documentPath);
        if (url.searchParams.has('revision') && url.searchParams.get('revision') !== revision) { json(response, 409, { error: 'This flow changed while preparing its screenshots. Save again to include the latest version.' }); return; }
        const node = document.nodes.find(item => item.id === decodeURIComponent(pathname.slice('/screens/'.length)));
        const profile = url.searchParams.get('profile');
        // Revision-bound manifest URLs distinguish a profile named "original"
        // from the legacy screenshot (whose manifest URL has no profile).
        const imagePath = profile && (profile !== 'original' || url.searchParams.has('revision')) ? node?.screenshots?.[profile]?.path : node?.screenshot;
        if (!imagePath) { json(response, 404, { error: 'Screen not captured for this profile.' }); return; }
        assetRoot = await realpath(dirname(documentPath));
        requestedPath = await realpath(resolve(assetRoot, imagePath));
        if (!['.png', '.jpg', '.jpeg', '.webp', '.gif'].includes(extname(requestedPath).toLowerCase())) { json(response, 415, { error: 'Use a PNG, JPEG, WebP or GIF screen image.' }); return; }
        if ((await stat(requestedPath)).size > 8 * 1024 * 1024) { json(response, 413, { error: 'Screen image exceeds 8 MB.' }); return; }
      } else {
        assetRoot = await realpath(viewerRoot);
        const localPath = pathname === '/' || pathname === '/design-system' ? 'index.html' : decodeURIComponent(pathname.slice(1));
        requestedPath = await realpath(resolve(assetRoot, localPath));
      }
      if (!isInside(assetRoot, requestedPath)) { json(response, 403, { error: 'Asset outside viewer scope.' }); return; }
      const type = types[extname(requestedPath).toLowerCase()];
      if (!type) { json(response, 404, { error: 'Asset not found.' }); return; }
      const body = await readFile(requestedPath);
      response.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-cache' });
      response.end(request.method === 'HEAD' ? undefined : body);
    } catch (error) {
      json(response, error.status || (error.code === 'ENOENT' ? 404 : 400), { error: error.code === 'ENOENT' ? 'Asset not found. Build the plugin viewer before starting it.' : error.status ? error.message : 'Could not read this viewer asset.' });
    }
  });
}

export async function main(args = process.argv.slice(2)) {
  if (args.includes('--help')) {
    console.log(`Flows viewer\n  ${launcherCommand('serve')} --file /path/to/journey.flows.json [--port 4317] [--project /path/to/app] [--app AppName] [--library /path/to/library]\n  The viewer binds to 127.0.0.1 and reloads when the file changes.`); return;
  }
  const options = {};
  for (let index = 0; index < args.length; index += 2) {
    if (!['--file', '--port', '--project', '--app', '--library'].includes(args[index]) || !args[index + 1]) throw new Error('Use --file <path> and optionally --port <number>.');
    options[args[index]] = args[index + 1];
  }
  const file = options['--file'] ? resolve(options['--file']) : resolve(pluginRoot, 'examples/checkout.flows.json');
  const port = Number(options['--port'] ?? 4317);
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Port must be between 0 and 65535.');
  await readDocument(file);
  await stat(resolve(pluginRoot, 'viewer/index.html'));
  const server = createFlowServer({ file, project: options['--project'], appName: options['--app'], libraryRoot: options['--library'] });
  server.on('error', error => { console.error(error.code === 'EADDRINUSE' ? `Port ${port} is in use. Choose another port with --port.` : error.message); process.exitCode = 1; });
  server.listen(port, '127.0.0.1', () => console.log(`Flows ready: http://127.0.0.1:${server.address().port}\nFlow: ${file}`));
  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
}
if (isEntrypoint(import.meta.url)) main().catch(error => { console.error(error.code === 'ENOENT' ? 'File missing. Check --file and run npm run plugin:build in the source checkout.' : error.message); process.exitCode = 1; });

SHA-256: 269458e0522c5520bdf3e83cf7bbd318de58d0da738b1e2154a5b4c10634ff4e