Skip to content
  1. Home
  2. workspace
Checking…
Demo view — sanitized data only. Sign in over HTTPS to create projects and manage the workspace.

AI Engineering Workspace

Partial

Chat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.

Project files

read-only

app/src/lib/workspace.ts

1// Project-scoped workspaces under data/workspaces/<projectId>. No arbitrary host paths, no shell: git is run via execFile with fixed argument vectors.
2import fs from "node:fs";
3import path from "node:path";
4import { execFile } from "node:child_process";
5import { DATA_DIR, db } from "./db";
6
7export const MAX_TEXT = 1_000_000, MAX_UPLOAD = 5_000_000;
8const ALLOWED_UPLOAD = new Set([".txt", ".md", ".json", ".csv", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".pdf", ".ts", ".tsx", ".js", ".jsx", ".css", ".html", ".yml", ".yaml", ".toml", ".py"]);
9const HIDDEN = new Set([".git"]);
10export class WsError extends Error { constructor(msg: string, public status = 400) { super(msg); } }
11
12export async function root(projectId: string, orgId: string): Promise<string> {
13 if (!/^[A-Za-z0-9_-]{1,64}$/.test(projectId)) throw new WsError("bad project id");
14 if (!(await db().prepare("SELECT id FROM projects WHERE id=? AND org_id=?").get(projectId, orgId))) throw new WsError("project not found", 404);
15 const r = path.join(DATA_DIR, "workspaces", projectId); fs.mkdirSync(r, { recursive: true, mode: 0o700 }); return fs.realpathSync(r);
16}
17/** Resolve a user path inside the workspace; rejects traversal, absolute paths, NULs, .git and any symlink escape. */
18export function safe(rootDir: string, rel: string, { allowRoot = false } = {}): string {
19 if (typeof rel !== "string" || rel.includes("\0") || rel.length > 300) throw new WsError("bad path");
20 if (path.isAbsolute(rel)) throw new WsError("absolute paths not allowed");
21 const parts = rel.split("/").filter(Boolean); if (!parts.length && !allowRoot) throw new WsError("path required");
22 if (parts.some(p => p === ".." || p === "." || HIDDEN.has(p))) throw new WsError("path not allowed");
23 const full = path.join(rootDir, ...parts);
24 let probe = full; while (!fs.existsSync(probe) && probe !== rootDir) probe = path.dirname(probe);
25 const real = fs.realpathSync(probe); if (real !== rootDir && !real.startsWith(rootDir + path.sep)) throw new WsError("path escapes workspace", 403);
26 if (fs.existsSync(full) && fs.lstatSync(full).isSymbolicLink()) throw new WsError("symlinks not allowed", 403);
27 return full;
28}
29export function list(rootDir: string, rel = "") {
30 const dir = safe(rootDir, rel, { allowRoot: true }); if (!fs.existsSync(dir)) return [];
31 return fs.readdirSync(dir, { withFileTypes: true }).filter(e => !HIDDEN.has(e.name) && !e.isSymbolicLink())
32 .map(e => ({ name: e.name, path: [rel, e.name].filter(Boolean).join("/"), dir: e.isDirectory(), size: e.isFile() ? fs.statSync(path.join(dir, e.name)).size : 0 }))
33 .sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name));
34}
35export function readText(rootDir: string, rel: string) {
36 const f = safe(rootDir, rel); if (!fs.existsSync(f) || !fs.statSync(f).isFile()) throw new WsError("not found", 404);
37 const st = fs.statSync(f); if (st.size > MAX_TEXT) throw new WsError("file too large to edit (1 MB limit)", 413);
38 const buf = fs.readFileSync(f); if (buf.includes(0)) throw new WsError("binary file", 415);
39 return { text: buf.toString("utf8"), size: st.size, mtime: st.mtimeMs };
40}
41export function writeText(rootDir: string, rel: string, text: string) {
42 if (Buffer.byteLength(text) > MAX_TEXT) throw new WsError("content too large (1 MB limit)", 413);
43 const f = safe(rootDir, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, text, { mode: 0o600 });
44}
45export function remove(rootDir: string, rel: string) { const f = safe(rootDir, rel); if (!fs.existsSync(f)) throw new WsError("not found", 404); fs.rmSync(f, { recursive: true, force: true }); }
46export function upload(rootDir: string, dirRel: string, name: string, buf: Buffer) {
47 if (!/^[\w][\w.\- ]{0,100}$/.test(name) || name.includes("..")) throw new WsError("bad file name");
48 const ext = path.extname(name).toLowerCase(); if (!ALLOWED_UPLOAD.has(ext)) throw new WsError(`file type ${ext || "(none)"} not allowed`, 415);
49 if (buf.length > MAX_UPLOAD) throw new WsError("file too large (5 MB limit)", 413);
50 const magic = (b: string) => buf.subarray(0, b.length).toString("latin1") === b;
51 if (ext === ".png" && !magic("\x89PNG")) throw new WsError("not a valid PNG", 415);
52 if ((ext === ".jpg" || ext === ".jpeg") && !(buf[0] === 0xff && buf[1] === 0xd8)) throw new WsError("not a valid JPEG", 415);
53 if (ext === ".pdf" && !magic("%PDF-")) throw new WsError("not a valid PDF", 415);
54 if (ext === ".svg" && /<script|onload\s*=|javascript:/i.test(buf.toString("utf8"))) throw new WsError("active content in SVG rejected", 415);
55 const f = safe(rootDir, [dirRel, name].filter(Boolean).join("/")); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, buf, { mode: 0o600 }); return path.relative(rootDir, f);
56}
57
58// ---- git: fixed argv only, never a shell, no user-controlled flags ----
59const git = (cwd: string, args: string[]) => new Promise<string>((res, rej) =>
60 execFile("git", ["-c", "core.hooksPath=/dev/null", "-c", "user.name=Zloud Studio", "-c", "user.email=studio@localhost", ...args], { cwd, timeout: 15_000, maxBuffer: 2_000_000, env: { PATH: process.env.PATH, HOME: cwd, GIT_CONFIG_NOSYSTEM: "1" } as unknown as NodeJS.ProcessEnv },
61 (e: Error | null, out: string, err: string) => e ? rej(new WsError((err || e.message).toString().slice(0, 300), 422)) : res(out)));
62export async function gitOp(rootDir: string, op: string, arg = "") {
63 if (!fs.existsSync(path.join(rootDir, ".git"))) { if (op === "init") { await git(rootDir, ["init", "-q", "-b", "main"]); return { ok: true }; } return { initialized: false }; }
64 switch (op) {
65 case "status": return { initialized: true, status: await git(rootDir, ["status", "--porcelain=v1", "-b", "-uall"]) };
66 case "diff": return { diff: (await git(rootDir, ["diff", "--no-color", "HEAD"]).catch(() => git(rootDir, ["diff", "--no-color"]))).slice(0, 200_000) };
67 case "log": return { log: (await git(rootDir, ["log", "--max-count=30", "--pretty=format:%h|%an|%ad|%s", "--date=iso"]).catch(() => "")) };
68 case "branches": return { branches: await git(rootDir, ["branch", "--list", "--no-color"]) };
69 case "commit": { const m = arg.trim().slice(0, 200); if (!m) throw new WsError("commit message required"); await git(rootDir, ["add", "-A"]); return { ok: true, out: await git(rootDir, ["commit", "-q", "-m", m]) }; }
70 case "branch": { if (!/^[A-Za-z0-9._\/-]{1,60}$/.test(arg) || arg.startsWith("-") || arg.includes("..")) throw new WsError("bad branch name"); await git(rootDir, ["switch", "-c", arg]); return { ok: true }; }
71 case "switch": { if (!/^[A-Za-z0-9._\/-]{1,60}$/.test(arg) || arg.startsWith("-") || arg.includes("..")) throw new WsError("bad branch name"); await git(rootDir, ["switch", arg]); return { ok: true }; }
72 case "init": return { ok: true, note: "already initialised" };
73 default: throw new WsError("unknown git operation");
74 }
75}
76

Conversation

Partial
Sign in to start AI sessions.

Task checklist

  • Application shell deployed
  • Persistent projects
  • Agent runtime
  • Sandboxed terminal

Execution activity

No agent sessions. Git HEAD 548ed73 on master.

Approval requests

None pending.