diff --git a/src/App.tsx b/src/App.tsx index c6719bac..85661e42 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -14,6 +14,13 @@ import { type ProjectCatalogEntry, } from "./projects/projectCatalogRuntime"; import { debugLog } from "./utils/debugLog"; +import { CuratedPublicLanding, CuratedExplorerShell } from "./public/CuratedExplorerShell"; +import { + attachPublicKeyboardGuard, + canOpenProject, + publicRouteUrl, + resolveGateAExperience, +} from "./public/gateAExperience"; import { SHAHBAZI_VIEWER_BACKGROUND } from "./projectModules/shahbazi/ui"; import "./App.css"; @@ -49,15 +56,30 @@ const EditorChrome = lazy(() => ); export function App() { + // Resolve once: direct public links and attempted editor deep-links fail closed. + const [experience] = useState(() => + resolveGateAExperience(window.location.search, import.meta.env.DEV), + ); const containerRef = useRef(null); const loadRequestRef = useRef(0); const initialProjectOpenedRef = useRef(false); const [project, setProject] = useState(null); - const [loadError, setLoadError] = useState(null); + const [loadError, setLoadError] = useState(experience.error); const [loadState, setLoadState] = useState("landing"); const [sceneHandle, setSceneHandle] = useState(null); - const openProject = useCallback((projectSlug: string = DEFAULT_PROJECT_SLUG) => { + const openProject = useCallback(( + projectSlug: string = DEFAULT_PROJECT_SLUG, + updatePublicUrl = true, + ) => { + // Behavior-boundary enforcement, not just removal of landing controls. + if (!canOpenProject(experience, projectSlug)) { + setLoadError("This project is unavailable in the public explorer."); + return; + } + if (experience.mode === "public" && updatePublicUrl) { + window.history.replaceState(window.history.state, "", publicRouteUrl(window.location.href, projectSlug)); + } const requestId = loadRequestRef.current + 1; loadRequestRef.current = requestId; setLoadError(null); @@ -78,22 +100,31 @@ export function App() { setLoadError(message); setLoadState("landing"); }); - }, []); + }, [experience]); const returnToLanding = useCallback(() => { + if (experience.mode === "public") { + window.history.replaceState(window.history.state, "", publicRouteUrl(window.location.href, null)); + } loadRequestRef.current += 1; setLoadError(null); setProject(null); setSceneHandle(null); setLoadState("landing"); - }, []); + }, [experience.mode]); useEffect(() => { if (initialProjectOpenedRef.current) return; initialProjectOpenedRef.current = true; - const slug = new URLSearchParams(window.location.search).get("project"); - if (slug) openProject(slug); - }, [openProject]); + if (experience.initialProjectSlug) { + openProject(experience.initialProjectSlug, false); + } + }, [experience.initialProjectSlug, openProject]); + + useEffect(() => { + if (experience.mode !== "public") return; + return attachPublicKeyboardGuard(window, Boolean(sceneHandle && project)); + }, [experience.mode, sceneHandle, project]); useEffect(() => { if (!containerRef.current || !project) return; @@ -148,17 +179,25 @@ export function App() { }, [project]); useEffect(() => { - if (!sceneHandle || !project || !import.meta.env.DEV) return; + if (!sceneHandle || !project || !import.meta.env.DEV || + experience.mode !== "developer") return; return installDevLayerDiagnostics(sceneHandle, { projectSlug: project.projectSlug, projectName: project.manifest.name, }); - }, [project, sceneHandle]); + }, [project, sceneHandle, experience.mode]); return (
- {loadState === "landing" && !project && ( + {loadState === "landing" && !project && experience.mode === "public" && ( + openProject(UTAH_FORGE_PROJECT.slug)} + /> + )} + {loadState === "landing" && !project && experience.mode === "developer" && ( )} - {sceneHandle && project && ( + {sceneHandle && project && experience.mode === "public" && ( + + )} + {sceneHandle && project && experience.mode === "developer" && ( void; + developmentAvailable: boolean; +} + +/** An explicit, single supported example. Other projects remain in the dev editor. */ +export function CuratedPublicLanding({ + error, + onOpenUtah, + developmentAvailable, +}: PublicLandingProps) { + return ( +
+
+

GeoSee · Geoscience visualization

+

+ Explore Utah FORGE +

+

+ Explore a prepared geothermal and geophysical visualization in a + browser. This public preview supports camera navigation only; + creating a project, importing files, authoring and saving are not + available here. +

+

+ Prepared source-derived layers may have unresolved survey registration + or datum limitations. Visualization is not validation of scientific + measurements or suitability for engineering decisions. +

+ {error &&

{error}

} + + {developmentAvailable && ( +

+ Working on GeoSee? Open developer editor +

+ )} +
+
+ ); +} + +interface PublicExplorerProps { + sceneHandle: SceneHandle; + project: LoadedProject; + onReturnHome: () => void; +} + +/** + * The public viewer mounts the existing read-only scene/page-state application + * path, never EditorProvider, EditorChrome or the dev Save/Import actions. + * Pages may supply optional camera/display presets, not application capability. + */ +export function CuratedExplorerShell({ + sceneHandle, + project, + onReturnHome, +}: PublicExplorerProps) { + return ( + + + + ); +} + +function PublicExplorerControls({ onReturnHome }: { onReturnHome: () => void }) { + const { resetToPose } = usePageController(); + + const handleReset = () => + performGateAAction("public", "view.reset", resetToPose); + + return ( +
+
+ +
Utah FORGE · Public viewer
+ +
+

+ Drag to orbit · Scroll to zoom · View-only. Scientific registration may + be unverified. Project editing, import, save and capture are unavailable. +

+
+ ); +} + +const landing: CSSProperties = { + position: "absolute", + inset: 0, + display: "grid", + placeItems: "center", + background: "linear-gradient(145deg, #0b1823, #1a3040 65%, #0a141c)", + color: "#f0f4f6", + fontFamily: "system-ui, sans-serif", + overflowY: "auto", + zIndex: 8, + padding: 24, + boxSizing: "border-box", +}; +const panel: CSSProperties = { + width: "min(640px, 100%)", + background: "rgba(13, 23, 31, 0.88)", + border: "1px solid rgba(190, 217, 226, 0.25)", + borderRadius: 18, + padding: "clamp(24px, 5vw, 48px)", + boxSizing: "border-box", + boxShadow: "0 24px 80px rgba(0,0,0,0.35)", +}; +const eyebrow: CSSProperties = { + fontSize: 12, + letterSpacing: "0.12em", + textTransform: "uppercase", + color: "#9ec9d4", + margin: "0 0 18px", +}; +const title: CSSProperties = { + fontSize: "clamp(34px, 5vw, 52px)", + lineHeight: 1.08, + fontWeight: 650, + margin: "0 0 22px", +}; +const description: CSSProperties = { + fontSize: 16, + lineHeight: 1.65, + color: "#dae4e8", +}; +const caveat: CSSProperties = { + fontSize: 13, + lineHeight: 1.6, + color: "#afc3cb", +}; +const primaryButton: CSSProperties = { + marginTop: 24, + background: "#dbf0f5", + color: "#0c2530", + border: 0, + borderRadius: 9, + padding: "12px 20px", + cursor: "pointer", + font: "600 15px system-ui, sans-serif", +}; +const errorStyle: CSSProperties = { + padding: 12, + color: "#ffe0df", + border: "1px solid #a95453", + borderRadius: 8, +}; +const developerNote: CSSProperties = { + marginTop: 24, + color: "#bbd1db", + fontSize: 12, +}; +const viewerOverlay: CSSProperties = { + position: "absolute", + inset: 0, + pointerEvents: "none", + zIndex: 12, + fontFamily: "system-ui, sans-serif", + color: "#f2f6f7", +}; +const viewerHeader: CSSProperties = { + position: "absolute", + left: 20, + right: 20, + top: 18, + display: "flex", + alignItems: "center", + gap: 12, + justifyContent: "space-between", +}; +const viewerTitle: CSSProperties = { + padding: "10px 14px", + background: "rgba(13,24,33,0.82)", + borderRadius: 9, + textAlign: "center", + fontSize: 14, +}; +const outlineButton: CSSProperties = { + pointerEvents: "auto", + background: "rgba(13,24,33,0.87)", + color: "#fff", + border: "1px solid rgba(228,242,247,0.55)", + borderRadius: 9, + padding: "10px 14px", + font: "500 13px system-ui, sans-serif", + cursor: "pointer", +}; +const viewerFooter: CSSProperties = { + position: "absolute", + bottom: 16, + left: "50%", + transform: "translateX(-50%)", + width: "min(720px, calc(100% - 32px))", + textAlign: "center", + background: "rgba(10,20,28,0.78)", + borderRadius: 9, + padding: "9px 12px", + fontSize: 12, + lineHeight: 1.5, +}; diff --git a/src/public/gateAExperience.ts b/src/public/gateAExperience.ts new file mode 100644 index 00000000..e39e0db7 --- /dev/null +++ b/src/public/gateAExperience.ts @@ -0,0 +1,187 @@ +/** + * G1-01 public experience contract. This controls only application behavior: + * it is not authentication or a server-side security boundary. + * The development write API must never be deployed on a public static host. + */ +export type GateAMode = "public" | "developer"; + +export type GateACapability = + | "project.open" + | "view.orbit" + | "view.pan" + | "view.zoom" + | "view.reset" + | "project.create" + | "project.import" + | "project.save" + | "project.write" + | "page.author" + | "layer.author" + | "presenter.launch" + | "capture.advanced" + | "keyboard.save" + | "dev.writeBatch"; + +export interface GateAExperience { + mode: GateAMode; + initialProjectSlug: string | null; + error: string | null; +} + +/** Project identity is stable; authored pages and their order are not authority. */ +export const GATE_A_CURATED_PROJECT_SLUG = "utah-forge" as const; + +const PUBLIC_CAPABILITIES: ReadonlySet = new Set([ + "project.open", + "view.orbit", + "view.pan", + "view.zoom", + "view.reset", +]); + +/** + * The editor is intentionally accessible only through ?mode=developer on a + * development build. Static public builds refuse the same direct URL. + */ +export function resolveGateAExperience( + search: string, + developmentBuild: boolean, +): GateAExperience { + const params = new URLSearchParams(search); + const mode = params.get("mode"); + const requestedProject = params.get("project"); + + if (mode === "developer") { + if (!developmentBuild) { + return { + mode: "public", + initialProjectSlug: null, + error: "The developer editor is available only in development builds.", + }; + } + return { + mode: "developer", + initialProjectSlug: requestedProject || null, + error: null, + }; + } + + if (mode !== null && mode !== "public") { + return { + mode: "public", + initialProjectSlug: null, + error: "This route is not supported in the public experience.", + }; + } + + if (requestedProject && requestedProject !== GATE_A_CURATED_PROJECT_SLUG) { + return { + mode: "public", + initialProjectSlug: null, + error: "That project is unavailable in the public explorer.", + }; + } + + return { + mode: "public", + initialProjectSlug: requestedProject || null, + error: null, + }; +} + +export function canUseGateACapability( + mode: GateAMode, + capability: GateACapability, +): boolean { + return mode === "developer" || PUBLIC_CAPABILITIES.has(capability); +} + +/** Explicitly reject attempted authoring actions rather than silently no-op. */ +export function requireGateACapability( + mode: GateAMode, + capability: GateACapability, +): void { + if (!canUseGateACapability(mode, capability)) { + throw new Error( + `Action "${capability}" is not available in the public explorer.`, + ); + } +} + +export function canOpenProject( + experience: GateAExperience, + projectSlug: string, +): boolean { + return ( + canUseGateACapability(experience.mode, "project.open") && + (experience.mode === "developer" || + projectSlug === GATE_A_CURATED_PROJECT_SLUG) + ); +} + +/** + * Run a public/developer action through the same policy used by the app. + * In particular, a denied action never evaluates an authoring callback. + */ +export function performGateAAction( + mode: GateAMode, + capability: GateACapability, + action: () => T, +): T { + requireGateACapability(mode, capability); + return action(); +} + +/** + * Public keyboard handler is installed at window capture phase so that a + * presenter/page controller registered later cannot consume disallowed keys. + * When the viewer is absent the public landing retains normal key navigation. + */ +export function attachPublicKeyboardGuard( + target: Window, + viewerActive: boolean, +): () => void { + const onKey = (event: KeyboardEvent) => { + const key = event.key; + const save = (event.ctrlKey || event.metaKey) && key.toLowerCase() === "s"; + const pageKey = + viewerActive && + (key === "ArrowRight" || + key === "ArrowLeft" || + key === "PageDown" || + key === "PageUp" || + key === "Home" || + key === "End"); + if (!save && !pageKey) return; + + // Match PageController's editable-target exemption for the page keys. + // Save remains disabled throughout the public experience. + const element = event.target as HTMLElement | null; + const editable = + element?.isContentEditable || + element?.tagName === "INPUT" || + element?.tagName === "TEXTAREA" || + element?.tagName === "SELECT"; + if (!save && editable) return; + + event.preventDefault(); + event.stopPropagation(); + event.stopImmediatePropagation(); + }; + target.addEventListener("keydown", onKey, true); + return () => target.removeEventListener("keydown", onKey, true); +} + +/** + * Normalize only the simple public landing/example URL; don't mutate the + * developer editor's route and don't introduce a second client router. + */ +export function publicRouteUrl(href: string, projectSlug: string | null): string { + if (projectSlug !== null && projectSlug !== GATE_A_CURATED_PROJECT_SLUG) { + throw new Error("This project is unavailable in the public explorer."); + } + const url = new URL(href); + url.search = ""; + if (projectSlug) url.searchParams.set("project", projectSlug); + return `${url.pathname}${url.search}${url.hash}`; +} diff --git a/tests/tools/gate-a-public-policy.test.mjs b/tests/tools/gate-a-public-policy.test.mjs new file mode 100644 index 00000000..a0709647 --- /dev/null +++ b/tests/tools/gate-a-public-policy.test.mjs @@ -0,0 +1,241 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import ts from "typescript"; + +const root = process.cwd(); +const source = () => readFileSync(resolve(root, "src/public/gateAExperience.ts"), "utf8"); +async function policy() { + const js = ts.transpileModule(source(), { + compilerOptions: { module: ts.ModuleKind.ES2022, target: ts.ScriptTarget.ES2022 }, + reportDiagnostics: true, + }); + assert.equal(js.diagnostics?.filter(d => d.category === ts.DiagnosticCategory.Error).length ?? 0, 0); + return import("data:text/javascript;base64," + Buffer.from(js.outputText).toString("base64")); +} + +test("public landing is the default without creating a project", async () => { + const { resolveGateAExperience } = await policy(); + assert.deepEqual(resolveGateAExperience("", false), { + mode: "public", initialProjectSlug: null, error: null, + }); +}); + +test("Utah FORGE is the only permitted public project route", async () => { + const { resolveGateAExperience, canOpenProject } = await policy(); + const route = resolveGateAExperience("?project=utah-forge", false); + assert.equal(route.mode, "public"); + assert.equal(route.initialProjectSlug, "utah-forge"); + assert.equal(canOpenProject(route, "utah-forge"), true); + assert.equal(canOpenProject(route, "woodjam"), false); + assert.equal(canOpenProject(route, "base-gui"), false); +}); + +test("invalid, unknown or misleading public routes fail closed with a visible error", async () => { + const { resolveGateAExperience } = await policy(); + for (const search of [ + "?project=unknown", "?project=woodjam", "?project=base-gui", + "?project=../utah-forge", "?mode=editor&project=utah-forge", + ]) { + const route = resolveGateAExperience(search, false); + assert.equal(route.mode, "public"); + assert.equal(route.initialProjectSlug, null); + assert.match(route.error, /unavailable|not supported|developer/i); + } +}); + +test("explicit developer workflow remains available only under a development build", async () => { + const { resolveGateAExperience, canOpenProject } = await policy(); + const dev = resolveGateAExperience("?mode=developer&project=woodjam", true); + assert.equal(dev.mode, "developer"); + assert.equal(dev.initialProjectSlug, "woodjam"); + assert.equal(canOpenProject(dev, "woodjam"), true); + const production = resolveGateAExperience("?mode=developer&project=woodjam", false); + assert.equal(production.mode, "public"); + assert.equal(production.initialProjectSlug, null); + assert.match(production.error, /development|unavailable/i); +}); + +test("public view actions are limited to safe navigation and inspection", async () => { + const { canUseGateACapability } = await policy(); + for (const action of ["project.open", "view.orbit", "view.pan", "view.zoom", "view.reset"]) { + assert.equal(canUseGateACapability("public", action), true, action); + } + assert.equal(canUseGateACapability("developer", "project.save"), true); +}); + +test("public authoring, import, save and keyboard save cannot cross the action boundary", async () => { + const { canUseGateACapability, requireGateACapability } = await policy(); + for (const action of [ + "project.create", "project.import", "project.save", "project.write", + "page.author", "layer.author", "presenter.launch", "capture.advanced", + "keyboard.save", "dev.writeBatch", + ]) { + assert.equal(canUseGateACapability("public", action), false, action); + assert.throws(() => requireGateACapability("public", action), /not available/i); + } +}); + +test("public route does not derive permissions from authored page IDs, titles, count or order", async () => { + const { resolveGateAExperience, canOpenProject } = await policy(); + for (const pageQuery of ["", "&page=00", "&page=archived-200", "&page=other&order=99"]) { + const route = resolveGateAExperience("?project=utah-forge" + pageQuery, false); + assert.equal(canOpenProject(route, "utah-forge"), true); + } + assert.doesNotMatch(source(), /pageOrder|pageId|pageTitle|pages\.length|archivedPages/); +}); + +test("App gates project loading and only mounts the editor in development mode", () => { + const app = readFileSync(resolve(root, "src/App.tsx"), "utf8"); + assert.match(app, /resolveGateAExperience/); + assert.match(app, /canOpenProject\(experience, projectSlug\)/); + assert.match(app, /experience\.mode === "developer" &&[\s\S]*? { + const shell = readFileSync(resolve(root, "src/public/CuratedExplorerShell.tsx"), "utf8"); + assert.match(shell, /PageControllerProvider/); + assert.doesNotMatch(shell, /<(?:EditorProvider|EditorRoot|EditorChrome|CaptureDirector|UtahForgeAddToProjectDrop)\b/); + assert.doesNotMatch(shell, /\b(?:writeFilesBatch|commitPending)\s*\(/); + const app = readFileSync(resolve(root, "src/App.tsx"), "utf8"); + assert.match(source(), /stopImmediatePropagation/); + assert.match(app, /attachPublicKeyboardGuard\(window, Boolean\(sceneHandle && project\)\)/); + assert.match(app, /experience\.mode !== "developer"\) return;\n return installDevLayerDiagnostics/); +}); + +test("production route denies developer mode regardless of direct query parameters", async () => { + const { resolveGateAExperience } = await policy(); + for (const query of ["?mode=developer", "?mode=developer&project=base-gui"]) { + const route = resolveGateAExperience(query, false); + assert.equal(route.mode, "public"); + assert.equal(route.initialProjectSlug, null); + } +}); + +function syntheticEvent(key, options = {}) { + return { + key, + ctrlKey: Boolean(options.ctrlKey), + metaKey: Boolean(options.metaKey), + altKey: Boolean(options.altKey), + target: options.target ?? { tagName: "DIV", isContentEditable: false }, + defaultPrevented: false, + immediateStopped: false, + preventDefault() { this.defaultPrevented = true; }, + stopPropagation() { this.propagationStopped = true; }, + stopImmediatePropagation() { this.immediateStopped = true; }, + }; +} + +function syntheticWindow() { + const listeners = []; + return { + listeners, + addEventListener(type, callback, capture) { listeners.push({ type, callback, capture }); }, + removeEventListener(type, callback, capture) { + const i = listeners.findIndex(x => x.type === type && x.callback === callback && x.capture === capture); + if (i >= 0) listeners.splice(i, 1); + }, + dispatch(event) { + for (const listener of [...listeners].sort((a, b) => Number(Boolean(b.capture)) - Number(Boolean(a.capture)))) { + if (event.immediateStopped) break; + if (listener.type === "keydown") listener.callback(event); + } + }, + }; +} + +test("R1: public viewer consumes page-navigation keys before presentation-page listeners", async () => { + const { attachPublicKeyboardGuard } = await policy(); + const host = syntheticWindow(); + const consumed = []; + const detach = attachPublicKeyboardGuard(host, true); + host.addEventListener("keydown", e => consumed.push(e.key), false); // pre-existing PageController listener + for (const key of ["ArrowRight", "ArrowLeft", "PageDown", "PageUp", "Home", "End"]) { + const event = syntheticEvent(key); + host.dispatch(event); + assert.equal(event.defaultPrevented, true, key); + assert.equal(event.immediateStopped, true, key); + } + assert.deepEqual(consumed, []); + detach(); + assert.equal(host.listeners.filter(x => x.capture === true).length, 0); +}); + +test("R1: public landing and editable elements retain normal arrow-key behavior", async () => { + const { attachPublicKeyboardGuard } = await policy(); + for (const viewerActive of [false, true]) { + const host = syntheticWindow(); + const consumed = []; + const detach = attachPublicKeyboardGuard(host, viewerActive); + host.addEventListener("keydown", e => consumed.push(e.key), false); + const editable = { tagName: "INPUT", isContentEditable: false }; + const a = syntheticEvent("ArrowLeft", { target: editable }); + host.dispatch(a); + assert.equal(a.defaultPrevented, false); + if (!viewerActive) { + const b = syntheticEvent("PageDown"); + host.dispatch(b); + assert.equal(b.defaultPrevented, false); + } + const ordinary = syntheticEvent("z"); + host.dispatch(ordinary); + assert.equal(ordinary.defaultPrevented, false); + assert.ok(consumed.length >= 2); + detach(); + } +}); + +test("R3: Ctrl/Cmd+S is captured in public mode, preventing a downstream save handler", async () => { + const { attachPublicKeyboardGuard } = await policy(); + for (const options of [{ ctrlKey: true }, { metaKey: true }]) { + for (const viewerActive of [false, true]) { + const host = syntheticWindow(); + let saves = 0; + const detach = attachPublicKeyboardGuard(host, viewerActive); + host.addEventListener("keydown", () => { saves += 1; }, false); + const event = syntheticEvent("S", options); + host.dispatch(event); + assert.equal(event.defaultPrevented, true); + assert.equal(saves, 0); + detach(); + } + } +}); + +test("R3: denied public actions never invoke their authoring/write callbacks; developer mode preserves them", async () => { + const { performGateAAction } = await policy(); + for (const capability of ["project.create", "project.import", "project.save", "project.write", "dev.writeBatch", "layer.author", "page.author", "presenter.launch", "capture.advanced"]) { + let writes = 0; + const action = () => { writes++; return "done"; }; + assert.throws(() => performGateAAction("public", capability, action), /not available/i); + assert.equal(writes, 0, capability); + assert.equal(performGateAAction("developer", capability, action), "done"); + assert.equal(writes, 1, capability); + } +}); + +test("R3: public App uses a capture-stage listener; editor is exclusive to developer mode", () => { + const app = readFileSync(resolve(root, "src/App.tsx"), "utf8"); + assert.match(app, /attachPublicKeyboardGuard\(window, Boolean\(sceneHandle && project\)\)/); + assert.match(app, /experience\.mode === "public" &&\s*\(\s* { + const { publicRouteUrl } = await policy(); + assert.equal(publicRouteUrl("https://example.test/geosee/?mode=developer&project=woodjam&page=123#viewer", "utah-forge"), "/geosee/?project=utah-forge#viewer"); + assert.equal(publicRouteUrl("https://example.test/geosee/?project=utah-forge&page=123#viewer", null), "/geosee/#viewer"); + assert.equal(publicRouteUrl("https://example.test/geosee/?project=utah-forge", null), "/geosee/"); + assert.throws(() => publicRouteUrl("https://example.test/?project=base-gui", "woodjam"), /unavailable|not supported/i); +}); + +test("R4: public App normalizes URL for CTA and Back, preserving developer URLs", () => { + const app = readFileSync(resolve(root, "src/App.tsx"), "utf8"); + assert.match(app, /window\.history\.replaceState\(window\.history\.state, "", publicRouteUrl\(window\.location\.href, projectSlug\)\)/); + assert.match(app, /window\.history\.replaceState\(window\.history\.state, "", publicRouteUrl\(window\.location\.href, null\)\)/); + assert.match(app, /if \(experience\.mode === "public" && updatePublicUrl\)/); +});