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>
This commit is contained in:
Adrian Perez
2026-04-18 19:29:28 +02:00
co-authored by Claude Opus 4.7
parent 42bd05db9c
commit e8d0b13ff5
81 changed files with 8933 additions and 1213 deletions
+16
View File
@@ -97,6 +97,21 @@ export interface ThumbnailGenerateEvent {
snapLevels?: boolean
}
export interface CameraControlFitSceneEvent {
/**
* XZ-plane axis-aligned bounds of the scene's geometry, computed from the
* scene graph (see `@pascal-app/editor`'s `computeSceneBoundsXZ`). The
* viewer's camera-controls listener frames the camera onto this box.
* Omitted values fall back to the camera's default pose.
*/
bounds?: {
min: [number, number]
max: [number, number]
center: [number, number]
size: [number, number]
}
}
type CameraControlEvents = {
'camera-controls:view': CameraControlEvent
'camera-controls:focus': CameraControlEvent
@@ -104,6 +119,7 @@ type CameraControlEvents = {
'camera-controls:top-view': undefined
'camera-controls:orbit-cw': undefined
'camera-controls:orbit-ccw': undefined
'camera-controls:fit-scene': CameraControlFitSceneEvent
'camera-controls:generate-thumbnail': ThumbnailGenerateEvent
}
+10 -9
View File
@@ -1,6 +1,7 @@
export type {
BuildingEvent,
CameraControlEvent,
CameraControlFitSceneEvent,
CeilingEvent,
DoorEvent,
EventSuffix,
@@ -37,7 +38,6 @@ export {
type Space,
wallTouchesOthers,
} from './lib/space-detection'
export { baseMaterial, glassMaterial } from './materials'
export {
getCatalogMaterialById,
getLibraryMaterialIdFromRef,
@@ -48,6 +48,7 @@ export {
type MaterialCatalogItem,
toLibraryMaterialRef,
} from './material-library'
export { baseMaterial, glassMaterial } from './materials'
export * from './schema'
export {
type ControlValue,
@@ -55,20 +56,14 @@ export {
useInteractive,
} from './store/use-interactive'
export { default as useLiveTransforms, type LiveTransform } from './store/use-live-transforms'
export { FenceSystem } from './systems/fence/fence-system'
export { clearSceneHistory, default as useScene } from './store/use-scene'
export { CeilingSystem } from './systems/ceiling/ceiling-system'
export { DoorSystem } from './systems/door/door-system'
export { FenceSystem } from './systems/fence/fence-system'
export { ItemSystem } from './systems/item/item-system'
export { RoofSystem } from './systems/roof/roof-system'
export { SlabSystem } from './systems/slab/slab-system'
export { StairSystem } from './systems/stair/stair-system'
export {
DEFAULT_WALL_HEIGHT,
DEFAULT_WALL_THICKNESS,
getWallPlanFootprint,
getWallThickness,
} from './systems/wall/wall-footprint'
export {
getClampedWallCurveOffset,
getMaxWallCurveOffset,
@@ -82,12 +77,18 @@ export {
normalizeWallCurveOffset,
sampleWallCenterline,
} from './systems/wall/wall-curve'
export {
DEFAULT_WALL_HEIGHT,
DEFAULT_WALL_THICKNESS,
getWallPlanFootprint,
getWallThickness,
} from './systems/wall/wall-footprint'
export {
calculateLevelMiters,
getWallMiterBoundaryPoints,
type Point2D,
type WallMiterBoundaryPoints,
pointToKey,
type WallMiterBoundaryPoints,
type WallMiterData,
} from './systems/wall/wall-mitering'
export { WallSystem } from './systems/wall/wall-system'
+141
View File
@@ -0,0 +1,141 @@
// @ts-expect-error — bun:test is provided by the Bun runtime; core does not
// depend on @types/bun so the import type is unresolved at compile time.
// The tsconfig in packages/core still emits this file; the @ts-expect-error
// keeps the build green while letting `bun test` pick it up normally.
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import { ALLOWED_ORIGINS_ENV, AssetUrl } from './asset-url'
function isValid(url: string): boolean {
return AssetUrl.safeParse(url).success
}
describe('AssetUrl', () => {
describe('allowed URLs', () => {
const cases: Array<[string, string]> = [
['asset://abc', 'internal asset handle'],
['asset://catalog/items/chair-1', 'nested asset handle'],
['blob:http://example.com/uuid-1234', 'blob URL with http inner'],
['blob:https://example.com/uuid-5678', 'blob URL with https inner'],
['https://cdn.example.com/a.glb', 'https CDN URL'],
['https://cdn.example.com/models/chair.glb?v=2', 'https URL with query string'],
['http://localhost:3000/x', 'http localhost with port'],
['http://localhost/x', 'http localhost without port'],
['http://127.0.0.1:8080/texture.png', 'http 127.0.0.1 loopback'],
['/public/a.glb', 'app-relative path'],
['/material/wood1/albedoMap_basecolor.jpg', 'relative path deep'],
['data:image/png;base64,AAA', 'inline PNG data URL'],
['data:image/jpeg;base64,/9j/', 'inline JPEG data URL'],
['data:image/webp;base64,UklGR', 'inline WebP data URL'],
['data:image/svg+xml,%3Csvg%3E', 'inline SVG data URL'],
]
for (const [url, label] of cases) {
test(`accepts ${label}: ${url}`, () => {
expect(isValid(url)).toBe(true)
})
}
})
describe('rejected URLs', () => {
const cases: Array<[string, string]> = [
['javascript:alert(1)', 'javascript scheme'],
['JAVASCRIPT:alert(1)', 'javascript scheme uppercase'],
['file:///etc/passwd', 'file scheme'],
['file://C:/Windows/System32/config', 'file scheme Windows'],
['http://evil.com/', 'non-loopback http'],
['http://example.com:3000/x', 'http on non-loopback host'],
['http://169.254.169.254/latest/meta-data/', 'http on link-local (cloud metadata)'],
['data:text/html,<script>alert(1)</script>', 'data text/html'],
['data:application/javascript,alert(1)', 'data application/javascript'],
['data:text/plain,hi', 'data text/plain'],
['ftp://a.b.com', 'ftp scheme'],
['ws://example.com/', 'websocket scheme'],
['vbscript:msgbox', 'vbscript scheme'],
['', 'empty string'],
['not a url at all', 'non-url string'],
['://missing-scheme', 'malformed'],
]
for (const [url, label] of cases) {
test(`rejects ${label}: ${url}`, () => {
expect(isValid(url)).toBe(false)
})
}
})
describe(`env allowlist via ${ALLOWED_ORIGINS_ENV}`, () => {
const g = globalThis as { process?: { env?: Record<string, string | undefined> } }
const original = g.process?.env?.[ALLOWED_ORIGINS_ENV]
beforeEach(() => {
if (g.process?.env) delete g.process.env[ALLOWED_ORIGINS_ENV]
})
afterEach(() => {
if (!g.process?.env) return
if (original === undefined) {
delete g.process.env[ALLOWED_ORIGINS_ENV]
} else {
g.process.env[ALLOWED_ORIGINS_ENV] = original
}
})
test('single origin allowlist accepts matching https URL', () => {
if (!g.process?.env) return // browser-only runtime
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app'
expect(isValid('https://cdn.pascal.app/a.glb')).toBe(true)
expect(isValid('https://cdn.pascal.app/deep/path?q=1')).toBe(true)
})
test('single origin allowlist rejects non-matching https URL', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app'
expect(isValid('https://cdn.other.com/a.glb')).toBe(false)
expect(isValid('https://attacker.example.com/x')).toBe(false)
})
test('multi-origin allowlist accepts any listed origin', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app, https://assets.pascal.app'
expect(isValid('https://cdn.pascal.app/a.glb')).toBe(true)
expect(isValid('https://assets.pascal.app/tex.webp')).toBe(true)
expect(isValid('https://third.example.com/x')).toBe(false)
})
test('allowlist ignores trailing / in URL path (origin match only)', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app'
expect(isValid('https://cdn.pascal.app/')).toBe(true)
expect(isValid('https://cdn.pascal.app')).toBe(true)
})
test('empty allowlist behaves like unset', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = ''
expect(isValid('https://cdn.other.com/a.glb')).toBe(true)
})
test('allowlist does not restrict non-https schemes', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app'
// these should still pass because they match earlier scheme-based branches
expect(isValid('asset://x')).toBe(true)
expect(isValid('blob:https://example.com/abc')).toBe(true)
expect(isValid('data:image/png;base64,AAA')).toBe(true)
expect(isValid('/public/a.glb')).toBe(true)
expect(isValid('http://localhost:3000/x')).toBe(true)
})
test('allowlist rejects subdomain spoofing', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app'
expect(isValid('https://cdn.pascal.app.evil.com/x')).toBe(false)
expect(isValid('https://evil.com/cdn.pascal.app')).toBe(false)
})
test('allowlist respects ports', () => {
if (!g.process?.env) return
g.process.env[ALLOWED_ORIGINS_ENV] = 'https://cdn.pascal.app:8443'
expect(isValid('https://cdn.pascal.app:8443/x')).toBe(true)
expect(isValid('https://cdn.pascal.app/x')).toBe(false)
})
})
})
+79
View File
@@ -0,0 +1,79 @@
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 }
+8 -8
View File
@@ -4,6 +4,13 @@ export { BaseNode, generateId, Material, nodeType, objectId } from './base'
export { CameraSchema } from './camera'
// Collections
export { type Collection, type CollectionId, generateCollectionId } from './collections'
export type {
MaterialMapProperties,
MaterialMaps,
MaterialPresetPayload,
MaterialTarget as MaterialTargetValue,
TextureWrapMode as TextureWrapModeValue,
} from './material'
// Material
export {
DEFAULT_MATERIALS,
@@ -14,15 +21,8 @@ export {
MaterialProperties,
MaterialSchema,
MaterialTarget,
TextureWrapMode,
resolveMaterial,
} from './material'
export type {
MaterialMapProperties,
MaterialMaps,
MaterialPresetPayload,
MaterialTarget as MaterialTargetValue,
TextureWrapMode as TextureWrapModeValue,
TextureWrapMode,
} from './material'
export { BuildingNode } from './nodes/building'
export { CeilingNode } from './nodes/ceiling'
+12 -11
View File
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { AssetUrl } from './asset-url'
export const MaterialPreset = z.enum([
'white',
@@ -30,7 +31,7 @@ export const MaterialSchema = z.object({
properties: MaterialProperties.optional(),
texture: z
.object({
url: z.string(),
url: AssetUrl,
repeat: z.tuple([z.number(), z.number()]).optional(),
scale: z.number().optional(),
})
@@ -56,16 +57,16 @@ export const TextureWrapMode = z.enum(['Repeat', 'ClampToEdge', 'MirroredRepeat'
export type TextureWrapMode = z.infer<typeof TextureWrapMode>
export const MaterialMapsSchema = z.object({
albedoMap: z.string().optional(),
metalnessMap: z.string().optional(),
roughnessMap: z.string().optional(),
normalMap: z.string().optional(),
displacementMap: z.string().optional(),
aoMap: z.string().optional(),
emissiveMap: z.string().optional(),
bumpMap: z.string().optional(),
alphaMap: z.string().optional(),
lightMap: z.string().optional(),
albedoMap: AssetUrl.optional(),
metalnessMap: AssetUrl.optional(),
roughnessMap: AssetUrl.optional(),
normalMap: AssetUrl.optional(),
displacementMap: AssetUrl.optional(),
aoMap: AssetUrl.optional(),
emissiveMap: AssetUrl.optional(),
bumpMap: AssetUrl.optional(),
alphaMap: AssetUrl.optional(),
lightMap: AssetUrl.optional(),
})
export type MaterialMaps = z.infer<typeof MaterialMapsSchema>
+2 -1
View File
@@ -1,10 +1,11 @@
import { z } from 'zod'
import { AssetUrl } from '../asset-url'
import { BaseNode, nodeType, objectId } from '../base'
export const GuideNode = BaseNode.extend({
id: objectId('guide'),
type: nodeType('guide'),
url: z.string(),
url: AssetUrl,
position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]),
rotation: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]),
scale: z.number().default(1),
+2 -1
View File
@@ -1,5 +1,6 @@
import dedent from 'dedent'
import { z } from 'zod'
import { AssetUrl } from '../asset-url'
import { BaseNode, nodeType, objectId } from '../base'
import type { CollectionId } from '../collections'
@@ -79,7 +80,7 @@ const assetSchema = z.object({
category: z.string(),
name: z.string(),
thumbnail: z.string(),
src: z.string(),
src: AssetUrl,
dimensions: z.tuple([z.number(), z.number(), z.number()]).default([1, 1, 1]), // [w, h, d]
attachTo: z.enum(['wall', 'wall-side', 'ceiling']).optional(),
tags: z.array(z.string()).optional(),
+2 -1
View File
@@ -1,10 +1,11 @@
import { z } from 'zod'
import { AssetUrl } from '../asset-url'
import { BaseNode, nodeType, objectId } from '../base'
export const ScanNode = BaseNode.extend({
id: objectId('scan'),
type: nodeType('scan'),
url: z.string(),
url: AssetUrl,
position: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]),
rotation: z.tuple([z.number(), z.number(), z.number()]).default([0, 0, 0]),
scale: z.number().default(1),