Add workspace editor tools

This commit is contained in:
Formsmith
2026-06-14 22:08:55 +03:00
parent 9a889fdcb7
commit 753a1c2833
29 changed files with 2849 additions and 1397 deletions
+60 -6
View File
@@ -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 });
+41 -2
View File
@@ -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 });
@@ -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) {