Adrian Perez e8d0b13ff5 feat(mcp,editor): Option A+B storage + 10 agent deliverables (Phase 7)
Ships the combined filesystem/Supabase storage adapter + MCP scene
lifecycle tools + Next.js API routes + editor /scene/[id] route, so
an MCP save is directly openable at /scene/<id> without any
injection hack. End-to-end verified: 10/10 e2e steps pass.

Storage (A1/A2/A3):
- SceneStore interface + error classes + slug helpers
- FilesystemSceneStore at $PASCAL_DATA_DIR (defaults XDG/~/.pascal)
  with atomic writes, .index sidecar, optimistic locking
- SupabaseSceneStore with scenes + scene_revisions tables, RLS
  migration SQL, mock-backed unit tests
- createSceneStore(env) auto-selects based on SUPABASE_URL +
  SUPABASE_SERVICE_ROLE_KEY

MCP tools (A4, A8, A9, A10):
- save_scene / load_scene / list_scenes / delete_scene / rename_scene
- list_templates / create_from_template (3 seed templates:
  empty-studio, two-bedroom, garden-house)
- generate_variants (7 mutation kinds, seeded RNG, save=true|false)
- photo_to_scene (vision sampling → scene graph → save)

Editor (A5, A6):
- /api/scenes + /api/scenes/[id] with RFC 7232 If-Match locking
- /scene/[id] and /scenes route pages with save button, SceneLoader
- Removed the window.__pascalScene dev injection hack

Security + UX edges (A7, A8):
- AssetUrl Zod validator: asset:// blob: data:image/ /path https:
  (http://localhost for dev) + PASCAL_ALLOWED_ASSET_ORIGINS env
  allowlist. Hardens scan.url, guide.url, item.asset.src,
  material.texture.url, MaterialMaps.*Map
- Auto-frame camera on empty→non-empty scene transition
  (camera-controls:fit-scene emitter event)

Shared utilities:
- rehydrateSiteChildren() extracted to packages/mcp/src/lib/ and
  used by both create-from-template and generate-variants to work
  around the SiteNode.children-as-objects vs. ids inconsistency
  (CROSS_CUTTING §2)
- Storage + MCP subpath exports added to packages/mcp/package.json
  (CROSS_CUTTING §4)

Tests: 293 pass / 0 fail across 40 files (was 142 pre-Phase-7).
Biome: clean.

Phase-7 e2e script at packages/mcp/test-reports/phase7-e2e.ts:
MCP HTTP + editor Next.js both point at $PASCAL_DATA_DIR =
/tmp/pascal-e2e, save_scene from MCP, GET /api/scenes/<id> from
editor server, /scenes list page renders all saved scenes, scene
page renders SceneLoader, delete_scene works.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 19:29:28 +02:00

80 lines
3.2 KiB
TypeScript

import { z } from 'zod'
/**
* Scheme allowlist for asset-like URLs embedded in scene graphs.
*
* Phase 3 security audit: `scan.url`, `guide.url`, `material.texture.url`, and
* `item.asset.src` were previously bare `z.string()`. That meant an
* attacker-crafted scene loaded in the editor could beacon to arbitrary URLs
* (e.g. `javascript:`, `file:///etc/passwd`, `http://169.254.169.254/...`).
*
* This validator rejects URLs that don't match the scheme allowlist below.
*/
const ALLOWED_SCHEMES = ['asset:', 'blob:', 'https:', 'data:image/'] as const
/**
* Optional environment variable that narrows which `https:` origins are
* accepted. Set to a comma-separated list (e.g. `https://cdn.pascal.app`).
* When unset, any `https:` origin is permitted.
*/
export const ALLOWED_ORIGINS_ENV = 'PASCAL_ALLOWED_ASSET_ORIGINS'
// Narrow access to the environment variable without requiring @types/node in
// this package. The core package ships to both browser and Node contexts.
function readAllowedOrigins(): readonly string[] | undefined {
const g = globalThis as { process?: { env?: Record<string, string | undefined> } }
const value = g.process?.env?.[ALLOWED_ORIGINS_ENV]
if (!value) return undefined
const list = value
.split(',')
.map((s: string) => s.trim())
.filter((s: string) => s.length > 0)
return list.length > 0 ? list : undefined
}
function isAllowedAssetUrl(url: string): boolean {
if (typeof url !== 'string' || url.length === 0) return false
if (url.startsWith('asset://')) return true // internal handle
if (url.startsWith('blob:')) return true // in-memory reference
if (url.startsWith('data:image/')) return true // inline image only (never data:text/html)
if (url.startsWith('/')) return true // app-relative path
try {
const parsed = new URL(url)
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false
// http is only permitted for localhost development
if (parsed.protocol === 'http:' && !['localhost', '127.0.0.1'].includes(parsed.hostname)) {
return false
}
// optional env-driven origin allowlist (only enforced for https URLs)
if (parsed.protocol === 'https:') {
const allowlist = readAllowedOrigins()
if (allowlist) return allowlist.includes(parsed.origin)
}
return true
} catch {
return false
}
}
/**
* Zod validator for asset-style URL fields. Accepts:
* - `asset://…` internal handles
* - `blob:…` in-memory references
* - `data:image/…` inline images (not `data:text/html` or other types)
* - `/…` app-relative paths
* - `https://…` public URLs (optionally narrowed to an env allowlist)
* - `http://localhost[:port]/…` or `http://127.0.0.1/…` for local dev
*
* Rejects every other scheme, including `javascript:`, `file:`, `ftp:`,
* and `data:text/html`, as well as empty strings and non-URL garbage.
*/
export const AssetUrl = z.string().refine(isAllowedAssetUrl, {
message:
'URL must be asset://, blob:, data:image/, /path, or https://. http://localhost allowed for dev.',
})
export type AssetUrl = z.infer<typeof AssetUrl>
// re-export the scheme allowlist for documentation / downstream validators
export { ALLOWED_SCHEMES }