diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ed4896e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: CI + +on: + push: + pull_request: + +jobs: + checks: + name: Typecheck and unit tests + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Typecheck + run: npm run typecheck + + - name: Unit tests + run: npm test diff --git a/README.md b/README.md index 5af3293..310b6ac 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,6 @@

- Live demo MIT license GitHub stars Local first diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index c45f199..19331c8 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -1,10 +1,17 @@ import type { NextConfig } from "next"; const isStaticExport = process.env.STATIC_EXPORT === "true"; +const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "") + .split(",") + .map((origin) => origin.trim()) + .filter(Boolean); const nextConfig: NextConfig = { devIndicators: false, - allowedDevOrigins: ["localhost", "127.0.0.1", "192.168.2.5"], + allowedDevOrigins: ["localhost", "127.0.0.1", ...extraAllowedDevOrigins], + env: { + NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false", + }, images: { unoptimized: true }, diff --git a/apps/web/public/assets/sketchforge/extrude-star-blue.png b/apps/web/public/assets/sketchforge/extrude-star-blue.png deleted file mode 100644 index 6d234a0..0000000 Binary files a/apps/web/public/assets/sketchforge/extrude-star-blue.png and /dev/null differ diff --git a/apps/web/public/assets/sketchforge/heart-red.png b/apps/web/public/assets/sketchforge/heart-red.png deleted file mode 100644 index 6d234a0..0000000 Binary files a/apps/web/public/assets/sketchforge/heart-red.png and /dev/null differ diff --git a/apps/web/public/assets/sketchforge/star-red.png b/apps/web/public/assets/sketchforge/star-red.png deleted file mode 100644 index 9e9bb61..0000000 Binary files a/apps/web/public/assets/sketchforge/star-red.png and /dev/null differ diff --git a/apps/web/src/app/api/codex-screenshot/route.ts b/apps/web/src/app/api/codex-screenshot/route.ts index e82932d..a12c4bb 100644 --- a/apps/web/src/app/api/codex-screenshot/route.ts +++ b/apps/web/src/app/api/codex-screenshot/route.ts @@ -2,7 +2,12 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { NextRequest, NextResponse } from "next/server"; -const localHosts = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]); +export const revalidate = false; + +const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]); +const PNG_DATA_URL_PREFIX = "data:image/png;base64,"; +const MAX_SCREENSHOT_BYTES = 25 * 1024 * 1024; +const MAX_SCREENSHOT_REQUEST_BYTES = Math.ceil((MAX_SCREENSHOT_BYTES * 4) / 3) + PNG_DATA_URL_PREFIX.length + 2048; function sanitizeFileName(value: unknown) { const fallback = `codex-screenshot-${Date.now()}.png`; @@ -13,22 +18,71 @@ function sanitizeFileName(value: unknown) { return cleaned.endsWith(".png") ? cleaned : `${cleaned || fallback}.png`; } +function isLocalSameOriginRequest(request: Request) { + const requestUrl = new URL(request.url); + if (!LOCAL_HOSTS.has(requestUrl.hostname)) { + return false; + } + + const origin = request.headers.get("origin"); + if (origin) { + try { + const originUrl = new URL(origin); + if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) { + return false; + } + } catch { + return false; + } + } + + const fetchSite = request.headers.get("sec-fetch-site"); + return !fetchSite || fetchSite === "same-origin" || fetchSite === "none"; +} + +function decodedBase64ByteLength(value: string) { + if (value.length % 4 === 1 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) { + return null; + } + const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0; + return Math.floor((value.length * 3) / 4) - padding; +} + export async function POST(request: NextRequest) { if (process.env.NODE_ENV === "production") { return NextResponse.json({ error: "Codex screenshot capture is only available in local development." }, { status: 404 }); } - const host = request.headers.get("host")?.split(":")[0] ?? ""; - if (!localHosts.has(host)) { + if (!isLocalSameOriginRequest(request)) { return NextResponse.json({ error: "Codex screenshot capture only accepts local requests." }, { status: 403 }); } - const body = (await request.json()) as { dataUrl?: unknown; name?: unknown }; - if (typeof body.dataUrl !== "string" || !body.dataUrl.startsWith("data:image/png;base64,")) { + const contentLength = Number(request.headers.get("content-length")); + if (Number.isFinite(contentLength) && contentLength > MAX_SCREENSHOT_REQUEST_BYTES) { + return NextResponse.json({ error: "Screenshot image is too large." }, { status: 413 }); + } + + let body: { dataUrl?: unknown; name?: unknown }; + try { + body = (await request.json()) as { dataUrl?: unknown; name?: unknown }; + } catch { + return NextResponse.json({ error: "Invalid screenshot request." }, { status: 400 }); + } + + if (typeof body.dataUrl !== "string" || !body.dataUrl.startsWith(PNG_DATA_URL_PREFIX)) { return NextResponse.json({ error: "Expected a PNG data URL." }, { status: 400 }); } - const bytes = Buffer.from(body.dataUrl.slice("data:image/png;base64,".length), "base64"); + const encodedImage = body.dataUrl.slice(PNG_DATA_URL_PREFIX.length); + const decodedBytes = decodedBase64ByteLength(encodedImage); + if (decodedBytes === null) { + return NextResponse.json({ error: "Expected a PNG data URL." }, { status: 400 }); + } + if (decodedBytes > MAX_SCREENSHOT_BYTES) { + return NextResponse.json({ error: "Screenshot image is too large." }, { status: 413 }); + } + + const bytes = Buffer.from(encodedImage, "base64"); const directory = path.join(process.cwd(), ".codex", "screenshots"); await mkdir(directory, { recursive: true }); diff --git a/apps/web/src/app/api/local-download/route.ts b/apps/web/src/app/api/local-download/route.ts index ef7cb90..fd09f49 100644 --- a/apps/web/src/app/api/local-download/route.ts +++ b/apps/web/src/app/api/local-download/route.ts @@ -2,26 +2,65 @@ import { promises as fs } from "fs"; import path from "path"; import { NextResponse } from "next/server"; +export const revalidate = false; + +const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]); +const MAX_LOCAL_DOWNLOAD_BYTES = 25 * 1024 * 1024; + function safeFileName(filename: string) { const base = path.basename(filename).replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim(); return base || "download.txt"; } +function isLocalSameOriginRequest(request: Request) { + const requestUrl = new URL(request.url); + if (!LOCAL_HOSTS.has(requestUrl.hostname)) { + return false; + } + + const origin = request.headers.get("origin"); + if (origin) { + try { + const originUrl = new URL(origin); + if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) { + return false; + } + } catch { + return false; + } + } + + const fetchSite = request.headers.get("sec-fetch-site"); + return !fetchSite || fetchSite === "same-origin" || fetchSite === "none"; +} + export async function POST(request: Request) { try { + if (!isLocalSameOriginRequest(request)) { + return NextResponse.json({ error: "Local folder downloads are only available from this localhost app" }, { status: 403 }); + } + const body = (await request.json()) as { content?: unknown; filename?: unknown; folder?: unknown }; if (typeof body.content !== "string" || typeof body.filename !== "string" || typeof body.folder !== "string") { return NextResponse.json({ error: "Invalid download request" }, { status: 400 }); } + if (Buffer.byteLength(body.content, "utf8") > MAX_LOCAL_DOWNLOAD_BYTES) { + return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 }); + } + const trimmedFolder = body.folder.trim(); if (!trimmedFolder) { return NextResponse.json({ error: "Choose a folder first" }, { status: 400 }); } - const targetDirectory = path.isAbsolute(trimmedFolder) ? trimmedFolder : path.join(process.cwd(), trimmedFolder); + const targetDirectory = path.resolve(path.isAbsolute(trimmedFolder) ? trimmedFolder : path.join(process.cwd(), trimmedFolder)); await fs.mkdir(targetDirectory, { recursive: true }); - const targetPath = path.join(targetDirectory, safeFileName(body.filename)); + const targetPath = path.resolve(targetDirectory, safeFileName(body.filename)); + const relativeTarget = path.relative(targetDirectory, targetPath); + if (relativeTarget.startsWith("..") || path.isAbsolute(relativeTarget)) { + return NextResponse.json({ error: "Invalid file path" }, { status: 400 }); + } await fs.writeFile(targetPath, body.content, "utf8"); return NextResponse.json({ path: targetPath }); diff --git a/apps/web/src/app/api/project-thumbnail/route.ts b/apps/web/src/app/api/project-thumbnail/route.ts index 343180e..5634b3c 100644 --- a/apps/web/src/app/api/project-thumbnail/route.ts +++ b/apps/web/src/app/api/project-thumbnail/route.ts @@ -2,7 +2,13 @@ import { promises as fs } from "fs"; import path from "path"; import { NextResponse } from "next/server"; +export const revalidate = false; + const THUMBNAIL_DIR = path.join(process.cwd(), ".codex", "project-thumbnails"); +const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]); +const PNG_DATA_URL_PREFIX = "data:image/png;base64,"; +const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024; +const MAX_THUMBNAIL_REQUEST_BYTES = Math.ceil((MAX_THUMBNAIL_BYTES * 4) / 3) + PNG_DATA_URL_PREFIX.length + 2048; function safeProjectId(projectId: string) { const clean = projectId.replace(/[^a-zA-Z0-9_-]/g, ""); @@ -17,7 +23,41 @@ function thumbnailPath(projectId: string) { return path.join(THUMBNAIL_DIR, `${safeId}.png`); } +function isLocalSameOriginRequest(request: Request) { + const requestUrl = new URL(request.url); + if (!LOCAL_HOSTS.has(requestUrl.hostname)) { + return false; + } + + const origin = request.headers.get("origin"); + if (origin) { + try { + const originUrl = new URL(origin); + if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) { + return false; + } + } catch { + return false; + } + } + + const fetchSite = request.headers.get("sec-fetch-site"); + return !fetchSite || fetchSite === "same-origin" || fetchSite === "none"; +} + +function decodedBase64ByteLength(value: string) { + if (value.length % 4 === 1 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) { + return null; + } + const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0; + return Math.floor((value.length * 3) / 4) - padding; +} + export async function GET(request: Request) { + if (!isLocalSameOriginRequest(request)) { + return new NextResponse("Project thumbnails are only available from this localhost app", { status: 403 }); + } + const projectId = new URL(request.url).searchParams.get("projectId") ?? ""; const filePath = thumbnailPath(projectId); if (!filePath) { @@ -38,6 +78,15 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + if (!isLocalSameOriginRequest(request)) { + return NextResponse.json({ error: "Project thumbnails are only available from this localhost app" }, { status: 403 }); + } + + const contentLength = Number(request.headers.get("content-length")); + if (Number.isFinite(contentLength) && contentLength > MAX_THUMBNAIL_REQUEST_BYTES) { + return NextResponse.json({ error: "Thumbnail image is too large" }, { status: 413 }); + } + let body: { dataUrl?: unknown; projectId?: unknown }; try { body = (await request.json()) as { dataUrl?: unknown; projectId?: unknown }; @@ -51,14 +100,22 @@ export async function POST(request: Request) { } const filePath = thumbnailPath(body.projectId); - const match = body.dataUrl.match(/^data:image\/png;base64,(.+)$/); - if (!filePath || !match) { + if (!filePath || !body.dataUrl.startsWith(PNG_DATA_URL_PREFIX)) { return NextResponse.json({ error: "Invalid thumbnail image" }, { status: 400 }); } + const encodedImage = body.dataUrl.slice(PNG_DATA_URL_PREFIX.length); + const decodedBytes = decodedBase64ByteLength(encodedImage); + if (decodedBytes === null) { + return NextResponse.json({ error: "Invalid thumbnail image" }, { status: 400 }); + } + if (decodedBytes > MAX_THUMBNAIL_BYTES) { + return NextResponse.json({ error: "Thumbnail image is too large" }, { status: 413 }); + } + await fs.mkdir(THUMBNAIL_DIR, { recursive: true }); await fs.rm(filePath, { force: true }); - await fs.writeFile(filePath, Buffer.from(match[1], "base64")); + await fs.writeFile(filePath, Buffer.from(encodedImage, "base64")); return NextResponse.json({ version: Date.now() }); } catch (error) { @@ -67,6 +124,10 @@ export async function POST(request: Request) { } export async function DELETE(request: Request) { + if (!isLocalSameOriginRequest(request)) { + return NextResponse.json({ error: "Project thumbnails are only available from this localhost app" }, { status: 403 }); + } + const projectId = new URL(request.url).searchParams.get("projectId") ?? ""; const filePath = thumbnailPath(projectId); if (!filePath) { diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 8ac29a5..82a5522 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -17,7 +17,6 @@ --nav-text: #31465d; --workplane: #9adcf0; --workplane-soft: rgba(154, 220, 240, 0.28); - --star: #ffd543; --shadow: 0 2px 6px rgba(35, 55, 75, 0.12); --font-ui: "Avenir Next", Avenir, "Helvetica Neue", Arial, sans-serif; } @@ -1367,40 +1366,6 @@ button { font-weight: 700; } -.ai-build-body { - width: 430px; -} - -.top-action-panel:has(.ai-build-body) { - width: 456px; -} - -.ai-build-body label { - display: grid; - gap: 6px; -} - -.ai-build-body label span { - color: #40586d; - font-size: 12px; - font-weight: 800; -} - -.ai-build-body textarea { - min-height: 104px; - resize: vertical; - padding: 9px; - color: #18364f; - background: #f8fbfd; - border: 1px solid #d6e2ea; - border-radius: 3px; - font: 12px/1.45 Consolas, "Courier New", monospace; -} - -.ai-build-body label:first-child textarea { - min-height: 154px; -} - .hidden-file-input { display: none; } @@ -3109,15 +3074,6 @@ button { text-shadow: 2px 2px 0 color-mix(in srgb, var(--shape-color), black 35%); } -.kind-star, -.kind-heart { - align-self: end; - color: var(--shape-color); - font-size: calc(var(--shape-size) * 0.78); - line-height: 1; - text-shadow: 2px 3px 0 color-mix(in srgb, var(--shape-color), black 26%); -} - .selection-outline { position: absolute; inset: 1px; diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx index 7015498..90ba6b8 100644 --- a/apps/web/src/app/page.tsx +++ b/apps/web/src/app/page.tsx @@ -3,6 +3,7 @@ import { Clock3, FileUp, Grid3X3, HomeIcon, List, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SketchForgeEditor, importedShapeFromStl } from "@/components/SketchForgeEditor"; +import { createLocalId } from "@/lib/localIds"; import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings"; import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge"; @@ -44,6 +45,7 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes"; const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode"; const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder"; const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"]; +const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true"; function formatUpdated(timestamp: number) { const age = Date.now() - timestamp; @@ -91,7 +93,18 @@ async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], re const database = await openProjectShapesDb(); return new Promise((resolve, reject) => { const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite"); - transaction.objectStore(PROJECT_SHAPES_STORE_NAME).put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord); + const store = transaction.objectStore(PROJECT_SHAPES_STORE_NAME); + const existingRequest = store.get(projectId); + existingRequest.onerror = () => { + transaction.abort(); + }; + existingRequest.onsuccess = () => { + const existing = existingRequest.result as ProjectShapeRecord | undefined; + if (existing && existing.revision > revision) { + return; + } + store.put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord); + }; transaction.oncomplete = () => { database.close(); resolve(); @@ -208,7 +221,7 @@ function mergeProjectsForStorage(projects: DashboardProject[]) { function newProject(name: string, index: number, shapeCount = 0): DashboardProject { const now = Date.now(); return { - id: crypto.randomUUID(), + id: createLocalId("project"), name, createdAt: now, updatedAt: now, @@ -240,6 +253,8 @@ export default function Home() { const [projectShapesById, setProjectShapesById] = useState>({}); const projectsJsonRef = useRef(""); const dashboardStlInputRef = useRef(null); + const nextProjectRevisionRef = useRef(0); + const projectShapeSaveQueuesRef = useRef>>({}); useEffect(() => { const { projects: storedProjects, legacyShapes } = readStoredProjects(); @@ -252,7 +267,7 @@ export default function Home() { }); }); } - setDownloadMode(window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY) === "folder" ? "folder" : "browser"); + setDownloadMode(!STATIC_EXPORT_BUILD && window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY) === "folder" ? "folder" : "browser"); setDownloadFolder(window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY) ?? ""); const params = new URLSearchParams(window.location.search); @@ -386,6 +401,17 @@ export default function Home() { const updateProjectSnapshot = useCallback((snapshot: { image: string; projectId: string; shapes: number }) => { const version = Date.now(); + if (STATIC_EXPORT_BUILD) { + setProjects((current) => + current.map((project) => + project.id === snapshot.projectId + ? { ...project, shapes: snapshot.shapes, thumbnailUrl: snapshot.image, thumbnailVersion: version, updatedAt: version } + : project, + ), + ); + return; + } + setProjects((current) => current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)), ); @@ -414,23 +440,42 @@ export default function Home() { }, []); const updateProjectShapes = useCallback((snapshot: { projectId: string; shapes: WorkplaneShape[] }) => { - const revision = Date.now(); - setProjectShapesById((current) => ({ - ...current, - [snapshot.projectId]: { revision, shapes: snapshot.shapes }, - })); - void saveProjectShapes(snapshot.projectId, snapshot.shapes, revision) + const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1); + nextProjectRevisionRef.current = revision; + setProjectShapesById((current) => { + const existing = current[snapshot.projectId]; + if (existing && existing.revision > revision) { + return current; + } + return { + ...current, + [snapshot.projectId]: { revision, shapes: snapshot.shapes }, + }; + }); + + const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve(); + const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, snapshot.shapes, revision)); + projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave; + + void queuedSave .then(() => { setProjects((current) => current.map((project) => - project.id === snapshot.projectId + project.id === snapshot.projectId && (project.revision ?? 0) <= revision ? { ...project, shapes: snapshot.shapes.length, updatedAt: revision, revision } : project, ), ); }) .catch((error) => { - setDashboardNotice(error instanceof Error ? error.message : "Could not save project shapes"); + if (projectShapeSaveQueuesRef.current[snapshot.projectId] === queuedSave) { + setDashboardNotice(error instanceof Error ? error.message : "Could not save project shapes"); + } + }) + .finally(() => { + if (projectShapeSaveQueuesRef.current[snapshot.projectId] === queuedSave) { + delete projectShapeSaveQueuesRef.current[snapshot.projectId]; + } }); }, []); @@ -521,7 +566,9 @@ export default function Home() { if (activeProjectId === projectId) { setActiveProjectId(null); } - void fetch(`/api/project-thumbnail?projectId=${encodeURIComponent(projectId)}`, { method: "DELETE" }); + if (!STATIC_EXPORT_BUILD) { + void fetch(`/api/project-thumbnail?projectId=${encodeURIComponent(projectId)}`, { method: "DELETE" }); + } void deleteProjectShapes(projectId).catch(() => { setDashboardNotice("Could not delete project shapes from local storage"); }); @@ -570,6 +617,7 @@ export default function Home() { projects={visibleProjects} query={query} settingsOpen={settingsOpen} + staticExportBuild={STATIC_EXPORT_BUILD} sortMode={sortMode} viewMode={viewMode} onCloseSettings={() => setSettingsOpen(false)} @@ -612,6 +660,7 @@ function Dashboard({ projects, query, settingsOpen, + staticExportBuild, sortMode, viewMode, onCloseSettings, @@ -633,6 +682,7 @@ function Dashboard({ projects: DashboardProject[]; query: string; settingsOpen: boolean; + staticExportBuild: boolean; sortMode: string; viewMode: ViewMode; onCloseSettings: () => void; @@ -805,15 +855,18 @@ function Dashboard({

@@ -5898,22 +5542,6 @@ function TopActionPanel({
) : null} - {panel === "builder" ? ( -
-