Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(cad): add the sandboxed cad-forge worker and its API-side prompt and params helpers

nirholas4d9df25e56a6
diff --git a/api/_lib/cad/forge.js b/api/_lib/cad/forge.js
new file mode 100644
index 000000000..4d795b378
--- /dev/null
+++ b/api/_lib/cad/forge.js
@@ -0,0 +1,138 @@
+// CAD Forge: sentence → build123d program → real B-rep part.
+//
+// The loop text-to-cad popularised, run server-side: a model writes the
+// program, workers/cad-forge builds it in a sandbox, and when the kernel
+// rejects it the real error (kind, message, failing line) goes back to the
+// model for a repair round. A design only ever reaches the user once the
+// geometry kernel has accepted it, so nothing shown is a guess.
+//
+// The program writer is the CAD model ladder (api/_lib/cad/writer.js), which
+// ends in the platform LLM chain. The builder is the worker at
+// GCP_CAD_FORGE_URL.
+
+import { writeCad } from './writer.js';
+import { parseDesign } from '../../../src/cad/params.js';
+import { CAD_SYSTEM, extractProgram, generateMessage, refineMessage, repairMessage } from './prompt.js';
+
+export const MAX_REPAIRS = 3;
+const BUILD_TIMEOUT_MS = 95_000;
+// The whole design (every write and build) must finish inside one request.
+export const FORGE_BUDGET_MS = 270_000;
+
+export class CadForgeError extends Error {
+ constructor(code, message, status = 502, detail = null) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ this.detail = detail;
+ }
+}
+
+export function cadWorkerConfigured() {
+ return Boolean(process.env.GCP_CAD_FORGE_URL && workerKey());
+}
+
+function workerKey() {
+ return process.env.CAD_FORGE_KEY || process.env.GCP_RECONSTRUCTION_KEY || '';
+}
+
+/**
+ * Build a program on the worker. Resolves to the worker's verdict: either
+ * { ok:true, metrics, artifacts } or { ok:false, error }. Throws CadForgeError
+ * only when the worker itself is unreachable or misconfigured.
+ */
+export async function buildProgram(code, { fetchImpl = fetch } = {}) {
+ if (!cadWorkerConfigured()) {
+ throw new CadForgeError('unconfigured', 'The CAD builder is not configured on this deployment.', 503);
+ }
+ const base = process.env.GCP_CAD_FORGE_URL.replace(/\/+$/, '');
+ let res;
+ try {
+ res = await fetchImpl(`${base}/build`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${workerKey()}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ code }),
+ signal: AbortSignal.timeout(BUILD_TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw new CadForgeError('builder_unreachable', 'The CAD builder did not respond. Try again in a moment.', 503, err?.message);
+ }
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ throw new CadForgeError('builder_failed', 'The CAD builder could not run this build. Try again in a moment.', 503, `${res.status} ${text.slice(0, 200)}`);
+ }
+ return res.json();
+}
+
+async function writeProgram({ user, track, deadline }) {
+ let completion;
+ try {
+ completion = await writeCad({ system: CAD_SYSTEM, user, deadline, track });
+ } catch (err) {
+ if (err?.status === 429) throw new CadForgeError('rate_limited', err.message, 429);
+ throw new CadForgeError('writer_unavailable', 'The CAD program writer is busy. Try again in a moment.', 503, err?.message);
+ }
+ const code = extractProgram(completion?.text);
+ return { code, model: completion?.model || null, provider: completion?.provider || null };
+}
+
+/**
+ * Write, build and repair until the kernel accepts the design.
+ *
+ * @param {object} opts
+ * @param {string} opts.prompt what the user asked for
+ * @param {string} [opts.baseCode] an existing program to refine
+ * @param {(event: object) => void} [opts.onEvent] progress: writing, building, repairing
+ * @param {object} [opts.track] spend-ledger attribution
+ * @returns {Promise<{ code, title, summary, params, build, attempts, model, provider }>}
+ */
+export async function forgeDesign({ prompt, baseCode = null, onEvent = () => {}, track = {}, buildImpl = buildProgram, writeImpl = writeProgram, budgetMs = FORGE_BUDGET_MS }) {
+ const deadline = Date.now() + budgetMs;
+ onEvent({ stage: 'writing', attempt: 1 });
+ let written = await writeImpl({ user: baseCode ? refineMessage(prompt, baseCode) : generateMessage(prompt), track, deadline });
+ const attempts = [];
+
+ for (let attempt = 1; attempt <= MAX_REPAIRS + 1; attempt++) {
+ if (!written.code) {
+ attempts.push({ attempt, error: { kind: 'writer', message: 'The writer returned no program.' } });
+ } else {
+ onEvent({ stage: 'building', attempt });
+ const build = await buildImpl(written.code);
+ if (build?.ok) {
+ const meta = parseDesign(written.code);
+ onEvent({ stage: 'built', attempt });
+ return {
+ code: written.code,
+ title: meta.title || titleFromPrompt(prompt),
+ summary: meta.summary,
+ params: meta.params,
+ build,
+ attempts: [...attempts, { attempt, ok: true }],
+ model: written.model,
+ provider: written.provider,
+ };
+ }
+ attempts.push({ attempt, error: build?.error || { kind: 'unknown', message: 'Build failed.' } });
+ }
+ // A repair needs a write and a build; without ~40 s left it cannot land.
+ if (attempt > MAX_REPAIRS || deadline - Date.now() < 40_000) break;
+ const last = attempts[attempts.length - 1].error;
+ onEvent({ stage: 'repairing', attempt: attempt + 1, error: last });
+ written = written.code
+ ? await writeImpl({ user: repairMessage({ request: prompt, code: written.code, error: last }), track, deadline })
+ : await writeImpl({ user: baseCode ? refineMessage(prompt, baseCode) : generateMessage(prompt), track, deadline });
+ }
+
+ const last = attempts[attempts.length - 1]?.error;
+ throw new CadForgeError(
+ 'design_failed',
+ 'The part could not be built after several attempts. Try describing it more concretely (shape, key dimensions, features).',
+ 422,
+ { attempts, lastError: last },
+ );
+}
+
+function titleFromPrompt(prompt) {
+ const words = String(prompt).trim().split(/\s+/).slice(0, 5).join(' ');
+ return words.charAt(0).toUpperCase() + words.slice(1);
+}
diff --git a/api/_lib/cad/prompt.js b/api/_lib/cad/prompt.js
new file mode 100644
index 000000000..203e43a4a
--- /dev/null
+++ b/api/_lib/cad/prompt.js
@@ -0,0 +1,104 @@
+// CAD Forge: the instructions that turn a sentence into a build123d program.
+//
+// Written against build123d 0.13 (OpenCascade 8), the version pinned in
+// workers/cad-forge/requirements.txt. Every API named in the reference block is
+// one the worker's build gate exercises or that the build123d docs list for
+// 0.13; a model that strays outside it gets the real traceback back in a repair
+// round (see api/_lib/cad/forge.js), so the reference only has to steer the
+// common case, not cover the library.
+
+export const CAD_SYSTEM = `You are a senior mechanical design engineer writing parametric CAD in Python with build123d 0.13 (OpenCascade). You turn one request into ONE manufacturable solid part.
+
+OUTPUT: exactly one fenced \`\`\`python block and nothing else. The program must follow this template:
+
+\`\`\`python
+# title: Short part name (2-5 words)
+# summary: One sentence on what it is and how it is used.
+from build123d import *
+import math
+
+WIDTH = 80 # Overall width [40..160 mm]
+DEPTH = 50 # Depth [30..120 mm]
+WALL = 2.4 # Wall thickness [1.2..6 mm]
+HOLE_D = 4.5 # Screw hole diameter [2..8 mm]
+
+with BuildPart() as part:
+ ...
+
+result = part.part
+\`\`\`
+
+PARAMETERS
+- Declare 3 to 8 key dimensions as top-level UPPERCASE constants, one per line, EXACTLY in the form: NAME = number # Label [min..max unit]
+- Use real-world sizes in millimetres. Ranges must contain the value and stay physically sensible. Counts use the unit "count" and integer values, e.g. SLOTS = 6 # Slot count [2..12 count]
+- Derive every other size from these constants so any slider value still builds. Guard derived sizes (e.g. fillet radius = min(2, WALL * 0.4)).
+
+MODELING RULES
+- Units are millimetres. Z is up. The part rests on the XY plane (its lowest point at Z = 0), centred on X and Y where natural.
+- Assign the finished solid to \`result\`. Import with \`from build123d import *\` and \`import math\`; standard parts come from bd_warehouse by name (see below); itertools and functools are also allowed. Never \`import build123d\` as a module. No file access, no printing needed, no other modules.
+- Prefer robust constructions: primitives, sketches extruded or revolved, booleans, Locations/GridLocations/PolarLocations patterns. Apply fillets and chamfers LAST and keep their radii below half the thinnest adjoining wall. Never fillet every edge blindly.
+- Keep it manufacturable: walls at least 1.2 mm for 3D printing, holes as real cylinders, no zero-thickness geometry, one connected solid unless the request clearly asks for several bodies.
+- No underscored attribute or name access, no eval/exec/getattr/open/type/str.format (use f-strings).
+
+BUILD123D 0.13 REFERENCE (builder mode)
+- with BuildPart() as p: ... then p.part. Inside: Box(l, w, h), Cylinder(radius, height), Sphere(radius), Cone(bottom_radius, top_radius, height), Torus(major_radius, minor_radius), Wedge(...).
+- Alignment: Box(10, 10, 5, align=(Align.CENTER, Align.CENTER, Align.MIN)) puts the bottom on the current plane.
+- Subtract with mode=Mode.SUBTRACT on any primitive or extrude, e.g. Cylinder(3, 20, mode=Mode.SUBTRACT).
+- Holes drill down from the current workplane: Hole(radius, depth=None), CounterBoreHole(radius, counter_bore_radius, counter_bore_depth), CounterSinkHole(radius, counter_sink_radius).
+- Workplane on a face: with Locations(p.faces().sort_by(Axis.Z)[-1]): ... (top face). with BuildSketch(p.faces().sort_by(Axis.Z)[-1]): ...
+- Patterns: with Locations((x, y, z), ...): / with GridLocations(x_spacing, y_spacing, x_count, y_count): / with PolarLocations(radius, count):
+- Sketches: with BuildSketch(Plane.XY) as s: Rectangle(w, h), RectangleRounded(w, h, radius), Circle(r), Ellipse(rx, ry), RegularPolygon(radius, side_count), SlotOverall(width, height), Polygon(*points), Text("ABC", font_size=8). Then extrude(amount=h) or extrude(amount=h, mode=Mode.SUBTRACT) or revolve(axis=Axis.Z).
+- Planes: Plane.XY, Plane.XZ, Plane.YZ, Plane.XY.offset(z), Plane.XZ.rotated((0, 0, 0)).
+- Profiles: with BuildSketch(Plane.XZ): with BuildLine(): Polyline((0,0), (10,0), (10,5), (0,5), close=True); make_face(). Then revolve(axis=Axis.Z) for turned parts.
+- Shelling: offset(amount=-WALL, openings=p.faces().sort_by(Axis.Z)[-1]) hollows a solid, leaving the top open.
+- Edge ops (last): fillet(p.edges().filter_by(Axis.Z), radius=r), chamfer(p.edges().group_by(Axis.Z)[-1], length=c).
+- Selectors: p.faces().sort_by(Axis.Z)[-1] (top), .sort_by(Axis.Z)[0] (bottom), p.edges().filter_by(Axis.Z) (vertical edges), p.edges().group_by(Axis.Z)[-1] (top ring of edges), .filter_by(GeomType.CIRCLE).
+- Mirror: mirror(about=Plane.YZ). Loft between sketches on offset planes: loft().
+- Algebra mode is also fine: result = Box(40, 20, 5) - Pos(0, 0, 0) * Cylinder(3, 5); Rot(0, 0, 45) * shape; shape.moved(Location((x, y, z))).
+
+STANDARD PARTS (bd_warehouse 0.4): use these instead of modeling gears, threads or fasteners by hand.
+- from bd_warehouse.gear import SpurGear: SpurGear(module, tooth_count, pressure_angle, thickness, root_fillet=None). Pitch diameter = module * tooth_count. Usable as a BuildPart object (adds to the part) or as a standalone solid; bore it with a Cylinder(..., mode=Mode.SUBTRACT) or Hole afterwards.
+- from bd_warehouse.thread import IsoThread: IsoThread(major_diameter, pitch, length, external=True, end_finishes=("fade", "square")). Combine with a core Cylinder of the minor diameter for a threaded rod.
+- from bd_warehouse.fastener import HexNut, SocketHeadCapScrew, PlainWasher, ClearanceHole, TapHole: HexNut("M8-1.25", fastener_type="iso4032"), SocketHeadCapScrew("M6-1", length=20, fastener_type="iso4762"), PlainWasher("M6", fastener_type="iso7089"). Sizes are strings such as "M3-0.5", "M4-0.7", "M5-0.8", "M6-1", "M8-1.25", "M10-1.5".
+- from bd_warehouse.bearing import SingleRowDeepGrooveBallBearing: SingleRowDeepGrooveBallBearing("M8-22-7", "SKT").
+- Standard parts already have their real dimensions; still expose 3 to 8 parameters for whatever you build around them (count, thickness, bore, spacing).
+
+EXACT SIGNATURES AND PITFALLS (these are the mistakes that fail builds)
+- 2D shapes (Rectangle, RectangleRounded, Circle, Ellipse, RegularPolygon, SlotOverall, SlotCenterToCenter, Polygon, Text, Trapezoid) exist ONLY inside BuildSketch. 3D primitives (Box, Cylinder, Sphere, Cone, Torus, Hole...) exist ONLY inside BuildPart.
+- Lines (Line, Polyline, Spline, ThreePointArc, CenterArc, RadiusArc, TangentArc) exist ONLY inside BuildLine. Close the outline, then call make_face() inside the enclosing BuildSketch.
+- There is no Hexagon, Square, Slot, Tube or Gear class. Hexagon: RegularPolygon(radius, 6) (radius is to the corners; for a flat-to-flat width W use W / math.sqrt(3)). Tube: Cylinder then Cylinder(..., mode=Mode.SUBTRACT).
+- GridLocations(x_spacing, y_spacing, x_count, y_count): all four are required. PolarLocations(radius, count). Locations takes tuples or Locations.
+- Shape.moved(Location((x, y, z), (rx, ry, rz))) takes ONE Location; there is no rotation= keyword. Or use Pos(x, y, z) * shape and Rot(rx, ry, rz) * shape.
+- extrude(amount=h) needs a pending sketch (made by a BuildSketch inside the BuildPart). revolve(axis=Axis.Z) needs a sketch drawn on a plane that contains the axis (Plane.XZ for Axis.Z).
+- Hole/CounterBoreHole/CounterSinkHole cut from the CURRENT workplane downward; put them under Locations on the top face, not at Z = 0 on the bottom.
+- Teeth, slots and fins: build one in a BuildSketch, then repeat it with PolarLocations/GridLocations inside that same sketch before extruding. Never boolean dozens of separate solids one by one.
+- Keep fillet radius strictly smaller than the thinnest wall it touches; when unsure use 0.5 to 1 mm.
+
+Think about the real object (how it is held, mounted, printed or machined) before writing. Output only the python block.`;
+
+/** The first-turn user message for a fresh request. */
+export function generateMessage(prompt) {
+ return `Request: ${prompt}\n\nWrite the complete build123d program.`;
+}
+
+/** The message for a refinement of an existing design. */
+export function refineMessage(prompt, code) {
+ return `Here is the current program:\n\n\`\`\`python\n${code}\n\`\`\`\n\nChange request: ${prompt}\n\nReturn the complete updated program. Keep the same parameter names where they still apply, keep the title unless the part changed identity, and keep every rule from the instructions.`;
+}
+
+/** The message that hands a failed build back to the model. */
+export function repairMessage({ request, code, error }) {
+ const lines = String(code).split('\n');
+ const where = error?.line ? `\nThe failing line ${error.line} is: ${String(lines[error.line - 1] ?? '').trim()}` : '';
+ return `Request: ${request}\n\nThis program failed to build:\n\n\`\`\`python\n${code}\n\`\`\`\n\nBuild error (${error?.kind || 'runtime'}): ${error?.message || 'unknown error'}${where}\n\nFix the cause and return the complete corrected program. If a fillet or chamfer failed, make it smaller or remove it. If a selector found nothing, select differently. Keep the parameters.`;
+}
+
+/** Pull the python program out of a completion. */
+export function extractProgram(text) {
+ const source = String(text || '');
+ // A completion cut off by its token budget can lose the closing fence, so
+ // an unterminated block still counts; the build will say if it is short.
+ const fenced = /```(?:python|py)?[ \t]*\n([\s\S]*?)(?:```|$)/i.exec(source);
+ const body = fenced ? fenced[1] : source.includes('from build123d') ? source : '';
+ return body.replace(/\r\n/g, '\n').trim();
+}
diff --git a/api/_lib/cad/store.js b/api/_lib/cad/store.js
new file mode 100644
index 000000000..e4272b27d
--- /dev/null
+++ b/api/_lib/cad/store.js
@@ -0,0 +1,273 @@
+// CAD Forge persistence: designs, their rebuilt variants, and their files.
+//
+// One row per design in `cad_designs`. A design is the build123d program, the
+// parameters parsed from it, the kernel's measurements, and the public URLs of
+// its exported files (STEP, STL, GLB, thumbnail and drawing SVGs) in object
+// storage under cad/<id>/. Refinements are designs too, linked by parent_id, so
+// a part's history is a chain of real, buildable programs.
+//
+// Moving a slider rebuilds the same program with new values. Each distinct set
+// of values is cached in `cad_variants` (keyed by paramsKey) with its files
+// under cad/<id>/v/<key>/, so a shared configuration link never rebuilds twice.
+//
+// Tables are created lazily, the same contract as diorama-store: without
+// DATABASE_URL every read returns null/empty and every write returns null.
+
+import { randomUUID } from 'node:crypto';
+import { sql } from '../db.js';
+import { databaseConfigured } from '../env.js';
+import { objectStorageConfigured, putObject, publicUrl } from '../r2.js';
+import { recordDailyActivity, maybeAwardFirstCreation } from '../streaks.js';
+
+export function cadStoreEnabled() {
+ return databaseConfigured() && objectStorageConfigured();
+}
+
+let _ensured = null;
+async function ensureTables() {
+ if (!cadStoreEnabled()) return false;
+ if (_ensured) return _ensured;
+ _ensured = (async () => {
+ await sql`
+ create table if not exists cad_designs (
+ id uuid primary key,
+ parent_id uuid,
+ title text not null,
+ summary text,
+ prompt text not null,
+ code text not null,
+ params jsonb not null default '[]'::jsonb,
+ metrics jsonb not null,
+ files jsonb not null,
+ adjustments jsonb not null default '[]'::jsonb,
+ model text,
+ user_id uuid,
+ views bigint not null default 0,
+ featured boolean not null default false,
+ created_at timestamptz not null default now()
+ )
+ `;
+ await sql`create index if not exists cad_designs_created_idx on cad_designs (created_at desc)`;
+ await sql`create index if not exists cad_designs_featured_idx on cad_designs (featured, created_at desc)`;
+ await sql`create index if not exists cad_designs_user_idx on cad_designs (user_id, created_at desc)`;
+ await sql`create index if not exists cad_designs_parent_idx on cad_designs (parent_id)`;
+ await sql`
+ create table if not exists cad_variants (
+ design_id uuid not null,
+ key text not null,
+ values jsonb not null,
+ metrics jsonb not null,
+ files jsonb not null,
+ adjustments jsonb not null default '[]'::jsonb,
+ created_at timestamptz not null default now(),
+ primary key (design_id, key)
+ )
+ `;
+ return true;
+ })().catch((err) => {
+ console.error('[cad-store] ensureTables failed:', err?.message);
+ _ensured = null;
+ return false;
+ });
+ return _ensured;
+}
+
+const ARTIFACTS = Object.freeze({
+ glb: { file: 'part.glb', type: 'model/gltf-binary' },
+ step: { file: 'part.step', type: 'model/step' },
+ stl: { file: 'part.stl', type: 'model/stl' },
+ thumb_svg: { file: 'thumb.svg', type: 'image/svg+xml' },
+ drawing_svg: { file: 'drawing.svg', type: 'image/svg+xml' },
+});
+
+/**
+ * Upload a build's base64 artifacts under `prefix`. Returns public URLs keyed
+ * like the worker's artifact map: { glb, step, stl, thumb_svg?, drawing_svg? }.
+ */
+export async function uploadArtifacts(prefix, artifacts) {
+ const entries = Object.entries(ARTIFACTS).filter(([key]) => typeof artifacts?.[key] === 'string');
+ const urls = {};
+ await Promise.all(
+ entries.map(async ([key, { file, type }]) => {
+ const objectKey = `${prefix}/${file}`;
+ await putObject({
+ key: objectKey,
+ body: Buffer.from(artifacts[key], 'base64'),
+ contentType: type,
+ metadata: { source: 'cad-forge' },
+ });
+ urls[key] = publicUrl(objectKey);
+ }),
+ );
+ return urls;
+}
+
+export function newDesignId() {
+ return randomUUID();
+}
+
+function toDesign(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ parentId: row.parent_id || null,
+ title: row.title,
+ summary: row.summary || null,
+ prompt: row.prompt,
+ code: row.code,
+ params: Array.isArray(row.params) ? row.params : [],
+ metrics: row.metrics,
+ files: row.files,
+ adjustments: Array.isArray(row.adjustments) ? row.adjustments : [],
+ model: row.model || null,
+ views: Number(row.views) || 0,
+ featured: Boolean(row.featured),
+ creatorUsername: row.creator_username || null,
+ createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
+ };
+}
+
+/** Persist a built design. Returns the stored design, or null when storage is off. */
+export async function saveDesign(design) {
+ if (!(await ensureTables())) return null;
+ const createdAt = new Date().toISOString();
+ try {
+ await sql`
+ insert into cad_designs (id, parent_id, title, summary, prompt, code, params, metrics, files, adjustments, model, user_id, created_at)
+ values (
+ ${design.id}, ${design.parentId || null}, ${design.title}, ${design.summary || null}, ${design.prompt},
+ ${design.code}, ${JSON.stringify(design.params || [])}::jsonb, ${JSON.stringify(design.metrics)}::jsonb,
+ ${JSON.stringify(design.files)}::jsonb, ${JSON.stringify(design.adjustments || [])}::jsonb,
+ ${design.model || null}, ${design.userId || null}, ${createdAt}
+ )
+ `;
+ } catch (err) {
+ console.error('[cad-store] saveDesign failed:', err?.message);
+ return null;
+ }
+ if (design.userId) {
+ recordDailyActivity(design.userId).catch(() => {});
+ maybeAwardFirstCreation(design.userId).catch(() => {});
+ }
+ return { ...design, views: 0, featured: false, createdAt };
+}
+
+export async function getDesign(id) {
+ if (!id || !(await ensureTables())) return null;
+ try {
+ const rows = await sql`
+ select d.*, u.username as creator_username
+ from cad_designs d
+ left join users u on u.id = d.user_id and u.deleted_at is null
+ where d.id = ${id}
+ limit 1
+ `;
+ return toDesign(rows[0]);
+ } catch (err) {
+ console.error('[cad-store] getDesign failed:', err?.message);
+ return null;
+ }
+}
+
+/** A design's lineage: its parent (if any) and its direct refinements. */
+export async function getLineage(id) {
+ if (!id || !(await ensureTables())) return { parent: null, children: [] };
+ try {
+ const rows = await sql`
+ select id, title, prompt, files->>'thumb_svg' as thumb, created_at, 'child' as rel
+ from cad_designs where parent_id = ${id}
+ union all
+ select p.id, p.title, p.prompt, p.files->>'thumb_svg', p.created_at, 'parent'
+ from cad_designs c join cad_designs p on p.id = c.parent_id
+ where c.id = ${id}
+ order by created_at asc
+ limit 40
+ `;
+ const card = (r) => ({ id: r.id, title: r.title, prompt: r.prompt, thumb: r.thumb || null });
+ return {
+ parent: rows.filter((r) => r.rel === 'parent').map(card)[0] || null,
+ children: rows.filter((r) => r.rel === 'child').map(card),
+ };
+ } catch (err) {
+ console.error('[cad-store] getLineage failed:', err?.message);
+ return { parent: null, children: [] };
+ }
+}
+
+export async function bumpViews(id) {
+ if (!id || !(await ensureTables())) return;
+ try {
+ await sql`update cad_designs set views = views + 1 where id = ${id}`;
+ } catch {
+ /* a missed view count is not worth surfacing */
+ }
+}
+
+/** Gallery cards: index columns and the thumbnail only, never the program. */
+export async function listDesigns({ scope = 'recent', limit = 24, q, userId } = {}) {
+ if (!(await ensureTables())) return [];
+ const lim = Math.min(60, Math.max(1, Number(limit) || 24));
+ const search = typeof q === 'string' && q.trim() ? `%${q.trim().slice(0, 120)}%` : null;
+ try {
+ const rows = userId
+ ? await sql`
+ select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
+ from cad_designs where user_id = ${userId}
+ order by created_at desc limit ${lim}`
+ : scope === 'featured'
+ ? await sql`
+ select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
+ from cad_designs where featured
+ order by created_at desc limit ${lim}`
+ : search
+ ? await sql`
+ select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
+ from cad_designs where title ilike ${search} or prompt ilike ${search}
+ order by created_at desc limit ${lim}`
+ : await sql`
+ select id, title, summary, prompt, files->>'thumb_svg' as thumb, metrics->'size_mm' as size_mm, views, created_at
+ from cad_designs
+ order by created_at desc limit ${lim}`;
+ return rows.map((r) => ({
+ id: r.id,
+ title: r.title,
+ summary: r.summary || null,
+ prompt: r.prompt,
+ thumb: r.thumb || null,
+ sizeMm: Array.isArray(r.size_mm) ? r.size_mm : null,
+ views: Number(r.views) || 0,
+ createdAt: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,
+ }));
+ } catch (err) {
+ console.error('[cad-store] listDesigns failed:', err?.message);
+ return [];
+ }
+}
+
+export async function getVariant(designId, key) {
+ if (!designId || !key || !(await ensureTables())) return null;
+ try {
+ const rows = await sql`select * from cad_variants where design_id = ${designId} and key = ${key} limit 1`;
+ const row = rows[0];
+ return row ? { key: row.key, values: row.values, metrics: row.metrics, files: row.files, adjustments: row.adjustments || [] } : null;
+ } catch (err) {
+ console.error('[cad-store] getVariant failed:', err?.message);
+ return null;
+ }
+}
+
+export async function saveVariant({ designId, key, values, metrics, files, adjustments }) {
+ if (!(await ensureTables())) return null;
+ try {
+ await sql`
+ insert into cad_variants (design_id, key, values, metrics, files, adjustments)
+ values (${designId}, ${key}, ${JSON.stringify(values)}::jsonb, ${JSON.stringify(metrics)}::jsonb,
+ ${JSON.stringify(files)}::jsonb, ${JSON.stringify(adjustments || [])}::jsonb)
+ on conflict (design_id, key) do nothing
+ `;
+ return { key, values, metrics, files, adjustments: adjustments || [] };
+ } catch (err) {
+ console.error('[cad-store] saveVariant failed:', err?.message);
+ return null;
+ }
+}
diff --git a/api/_lib/cad/writer.js b/api/_lib/cad/writer.js
new file mode 100644
index 000000000..49a2c43a7
--- /dev/null
+++ b/api/_lib/cad/writer.js
@@ -0,0 +1,124 @@
+// CAD Forge program writer: the model ladder that writes build123d.
+//
+// The platform chain (api/_lib/llm.js) caps every rung at ~12 s so chat fails
+// over fast. A complete parametric program is 2-4K tokens of exact Python and
+// the models that write it well take 20-120 s, so CAD gets its own ladder, in
+// the same shape as api/_lib/x-content/llm.js: strongest first, each rung with
+// a timeout sized for code, a 429 retried once after a pause, and the general
+// chain as the last rung so a write is never refused while anything answers.
+//
+// Order was set by a bake-off on 2026-10-09 against the real worker (six
+// prompts that defeated the general chain): Kimi K3 built every design it was
+// not rate limited on, mostly first try; Nemotron Super needed repair rounds
+// but converges; GLM 5.3 returned no program within two minutes and is not
+// used. All NIM rungs are free on the platform NVIDIA key.
+
+import { llmComplete } from '../llm.js';
+import { recordEvent } from '../usage.js';
+
+const NIM_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
+const GROQ_URL = 'https://api.groq.com/openai/v1/chat/completions';
+const MAX_TOKENS = 4_000;
+const RETRY_PAUSE_MS = 3_000;
+
+export const CAD_WRITER_MODEL_DEFAULT = 'moonshotai/kimi-k3';
+
+export function writerRungs(env = process.env) {
+ const rungs = [];
+ if (env.NVIDIA_API_KEY) {
+ rungs.push({ name: 'nvidia', url: NIM_URL, key: env.NVIDIA_API_KEY, model: env.CAD_WRITER_MODEL || CAD_WRITER_MODEL_DEFAULT, timeoutMs: 150_000 });
+ rungs.push({ name: 'nvidia', url: NIM_URL, key: env.NVIDIA_API_KEY, model: 'nvidia/nemotron-3-super-120b-a12b', timeoutMs: 60_000 });
+ }
+ if (env.GROQ_API_KEY) {
+ rungs.push({ name: 'groq', url: GROQ_URL, key: env.GROQ_API_KEY, model: 'openai/gpt-oss-120b', timeoutMs: 45_000 });
+ }
+ return rungs;
+}
+
+function isRetryable(status, body) {
+ if (status >= 500) return true;
+ return status === 429 && !/billing|credit|quota exceeded for|insufficient|not active/i.test(String(body));
+}
+
+const pause = (ms) => new Promise((done) => setTimeout(done, ms));
+
+async function callRung(rung, { system, user, deadline, fetchImpl }) {
+ for (let attempt = 1; attempt <= 2; attempt++) {
+ const budget = Math.min(rung.timeoutMs, deadline - Date.now());
+ if (budget < 5_000) return { error: 'budget exhausted' };
+ const started = Date.now();
+ let res;
+ try {
+ res = await fetchImpl(rung.url, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${rung.key}`, 'content-type': 'application/json' },
+ body: JSON.stringify({
+ model: rung.model,
+ max_tokens: MAX_TOKENS,
+ temperature: 0.2,
+ messages: [
+ { role: 'system', content: system },
+ { role: 'user', content: user },
+ ],
+ ...(rung.name === 'nvidia' ? { chat_template_kwargs: { enable_thinking: false, thinking: false } } : {}),
+ }),
+ signal: AbortSignal.timeout(Math.floor(budget)),
+ });
+ } catch (err) {
+ return { error: `unreachable: ${err?.message}` };
+ }
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ if (attempt === 1 && isRetryable(res.status, body)) {
+ await pause(RETRY_PAUSE_MS);
+ continue;
+ }
+ return { error: `${res.status} ${body.slice(0, 160)}` };
+ }
+ const data = await res.json().catch(() => null);
+ const text = data?.choices?.[0]?.message?.content;
+ if (typeof text !== 'string' || !text.trim()) return { error: 'empty completion' };
+ return {
+ text,
+ latencyMs: Date.now() - started,
+ usage: { input: data?.usage?.prompt_tokens || 0, output: data?.usage?.completion_tokens || 0 },
+ };
+ }
+ return { error: 'retries exhausted' };
+}
+
+/**
+ * Write (or rewrite) a program. Returns { text, provider, model }. Throws the
+ * general chain's error only when every rung, the general chain included, fails.
+ */
+export async function writeCad({ system, user, deadline = Date.now() + 180_000, track = {}, fetchImpl = fetch, env = process.env }) {
+ const failures = [];
+ for (const rung of writerRungs(env)) {
+ const out = await callRung(rung, { system, user, deadline, fetchImpl });
+ if (out.text) {
+ recordEvent({
+ kind: 'llm',
+ provider: rung.name,
+ model: rung.model,
+ inputTokens: out.usage.input,
+ outputTokens: out.usage.output,
+ costMicroUsd: 0,
+ latencyMs: out.latencyMs,
+ userId: track.userId ?? null,
+ tool: 'cad-forge',
+ });
+ return { text: out.text, provider: rung.name, model: rung.model };
+ }
+ failures.push(`${rung.model}: ${out.error}`);
+ }
+ if (failures.length) console.warn('[cad-writer] ladder exhausted, using the general chain:', failures.join(' | '));
+ const remaining = deadline - Date.now();
+ const completion = await llmComplete({
+ system,
+ user,
+ maxTokens: MAX_TOKENS,
+ timeoutMs: Math.max(20_000, remaining),
+ track: { tool: 'cad-forge', ...track },
+ });
+ return { text: completion?.text || '', provider: completion?.provider || null, model: completion?.model || null };
+}
diff --git a/src/cad/params.js b/src/cad/params.js
new file mode 100644
index 000000000..c61112947
--- /dev/null
+++ b/src/cad/params.js
@@ -0,0 +1,144 @@
+// CAD Forge: the parameter contract shared by the browser and the API.
+//
+// A CAD Forge design is a plain build123d Python program. Its tunable
+// dimensions are ordinary top-level constants annotated with a label and a
+// range, so the file stays runnable anywhere build123d is installed (and in
+// text-to-cad, which uses the same kernel):
+//
+// # title: Wall-mount phone holder
+// WIDTH = 80 # Overall width [40..160 mm]
+// WALL = 2.4 # Wall thickness [1.2..6 mm]
+//
+// parseDesign() reads those lines into slider definitions, and applyParams()
+// rewrites only the value on each matching line. Nothing else in the program is
+// ever touched, so what the sliders build is exactly the source a user sees and
+// downloads.
+
+export const MAX_PARAMS = 12;
+export const MAX_TITLE_LEN = 80;
+export const MAX_PROMPT_LEN = 600;
+
+const NUM = String.raw`-?\d+(?:\.\d+)?`;
+const PARAM_LINE = new RegExp(
+ String.raw`^([A-Z][A-Z0-9_]{0,39})(\s*=\s*)(${NUM})(\s*#\s*)(.+?)\s*\[\s*(${NUM})\s*\.\.\s*(${NUM})\s*([A-Za-z°%]*)\s*\]\s*$`,
+);
+const TITLE_LINE = /^#\s*title\s*:\s*(.+?)\s*$/i;
+const SUMMARY_LINE = /^#\s*summary\s*:\s*(.+?)\s*$/i;
+
+function decimals(text) {
+ const dot = text.indexOf('.');
+ return dot === -1 ? 0 : text.length - dot - 1;
+}
+
+/** Slider step for a parameter: integers step by 1, decimals by their precision. */
+function stepFor(valueText, minText, maxText) {
+ const places = Math.max(decimals(valueText), decimals(minText), decimals(maxText));
+ if (places === 0) return 1;
+ return Number((10 ** -Math.min(places, 3)).toFixed(3));
+}
+
+/**
+ * Read a design's title, one-line summary and parameters from its source.
+ * @param {string} code
+ * @returns {{ title: string|null, summary: string|null, params: Array<{name:string,label:string,value:number,min:number,max:number,step:number,unit:string,line:number}> }}
+ */
+export function parseDesign(code) {
+ const out = { title: null, summary: null, params: [] };
+ const lines = String(code || '').split('\n');
+ const seen = new Set();
+ lines.forEach((raw, index) => {
+ const line = raw.replace(/\r$/, '');
+ if (!out.title) {
+ const t = TITLE_LINE.exec(line);
+ if (t) out.title = t[1].slice(0, MAX_TITLE_LEN);
+ }
+ if (!out.summary) {
+ const s = SUMMARY_LINE.exec(line);
+ if (s) out.summary = s[1].slice(0, 240);
+ }
+ const m = PARAM_LINE.exec(line);
+ if (!m || seen.has(m[1]) || out.params.length >= MAX_PARAMS) return;
+ let min = Number(m[6]);
+ let max = Number(m[7]);
+ if (min > max) [min, max] = [max, min];
+ const value = Number(m[3]);
+ if (![value, min, max].every(Number.isFinite) || min === max) return;
+ seen.add(m[1]);
+ out.params.push({
+ name: m[1],
+ label: m[5].trim().slice(0, 60),
+ value: Math.min(max, Math.max(min, value)),
+ min,
+ max,
+ step: stepFor(m[3], m[6], m[7]),
+ unit: m[8] || '',
+ line: index + 1,
+ });
+ });
+ return out;
+}
+
+function formatValue(value, step) {
+ if (step >= 1) return String(Math.round(value));
+ const places = Math.min(3, decimals(String(step)));
+ return String(Number(value.toFixed(places)));
+}
+
+/**
+ * Rewrite parameter values in a program. Unknown names are ignored, values are
+ * clamped to each parameter's declared range and snapped to its step.
+ * @param {string} code
+ * @param {Record<string, number>} values
+ * @returns {{ code: string, applied: Record<string, number> }}
+ */
+export function applyParams(code, values = {}) {
+ const applied = {};
+ const wanted = values && typeof values === 'object' ? values : {};
+ const lines = String(code || '').split('\n');
+ const { params } = parseDesign(code);
+ const byLine = new Map(params.map((p) => [p.line - 1, p]));
+ for (const [index, param] of byLine) {
+ if (!Object.prototype.hasOwnProperty.call(wanted, param.name)) continue;
+ const raw = Number(wanted[param.name]);
+ if (!Number.isFinite(raw)) continue;
+ const snapped = Math.round(raw / param.step) * param.step;
+ const value = Math.min(param.max, Math.max(param.min, snapped));
+ const text = formatValue(value, param.step);
+ lines[index] = lines[index].replace(PARAM_LINE, (_all, name, eq, _v, hash, label, min, max, unit) =>
+ `${name}${eq}${text}${hash}${label} [${min}..${max}${unit ? ` ${unit}` : ''}]`,
+ );
+ applied[param.name] = Number(text);
+ }
+ return { code: lines.join('\n'), applied };
+}
+
+/** Current parameter values as a plain object. */
+export function paramValues(code) {
+ return Object.fromEntries(parseDesign(code).params.map((p) => [p.name, p.value]));
+}
+
+/** Stable short key for a set of values (cache key for rebuilt variants). */
+export function paramsKey(values) {
+ const entries = Object.entries(values || {}).sort(([a], [b]) => a.localeCompare(b));
+ let h = 2166136261;
+ for (const ch of JSON.stringify(entries)) {
+ h ^= ch.charCodeAt(0);
+ h = Math.imul(h, 16777619) >>> 0;
+ }
+ return h.toString(36);
+}
+
+// Densities in g/cm³ for the mass estimates on the design page.
+export const MATERIALS = Object.freeze([
+ { id: 'pla', label: 'PLA', density: 1.24 },
+ { id: 'petg', label: 'PETG', density: 1.27 },
+ { id: 'nylon', label: 'Nylon PA12', density: 1.01 },
+ { id: 'aluminum', label: 'Aluminium 6061', density: 2.7 },
+ { id: 'steel', label: 'Steel', density: 7.85 },
+ { id: 'brass', label: 'Brass', density: 8.5 },
+]);
+
+/** Mass in grams for a volume in mm³. */
+export function massGrams(volumeMm3, density) {
+ return (Number(volumeMm3) / 1000) * Number(density);
+}
diff --git a/workers/cad-forge/Dockerfile b/workers/cad-forge/Dockerfile
new file mode 100644
index 000000000..49c052b44
--- /dev/null
+++ b/workers/cad-forge/Dockerfile
@@ -0,0 +1,28 @@
+FROM python:3.11-slim
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1
+
+# OpenCascade links against the GL/X stubs even headless; libseccomp2 backs
+# pyseccomp, which is what keeps a model-written program off the network.
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ libgl1 libglib2.0-0 libgomp1 libseccomp2 libxrender1 libxext6 libsm6 \
+ && rm -rf /var/lib/apt/lists/*
+
+COPY requirements.txt /app/requirements.txt
+RUN pip install -r /app/requirements.txt
+
+WORKDIR /app
+COPY worker_security.py cad_policy.py sandbox_child.py main.py /app/
+# The sandbox child runs as nobody and must be able to read its own code.
+RUN chmod 0755 /app && chmod 0644 /app/*.py
+
+# Build gate: the policy unit tests plus real builds and real escape attempts
+# through the sandbox, run as root exactly like Cloud Run. A regression in the
+# sandbox fails the image instead of reaching production.
+COPY test_cad_policy.py test_sandbox.py /app/
+RUN python test_cad_policy.py && REQUIRE_SECCOMP=1 python test_sandbox.py
+
+EXPOSE 8080
+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]
diff --git a/workers/cad-forge/README.md b/workers/cad-forge/README.md
new file mode 100644
index 000000000..3c213928b
--- /dev/null
+++ b/workers/cad-forge/README.md
@@ -0,0 +1,31 @@
+# cad-forge
+
+Sandboxed worker that turns a build123d program into a real B-rep part (STEP, STL, GLB, optional SVG thumbnail and drawing).
+
+## API
+
+- `POST /build` with `{ "code": "<build123d program>" }`. Returns `200 { ok, metrics, artifacts, log, elapsed_s }`. A program that fails is still a 200 with `ok: false` and an `error` object so the caller can feed it back to the model for a repair round. Artifacts are base64.
+- `GET /health` returns `{ ok, warm, max_concurrent, seccomp_required, build123d }`.
+
+Every request needs the `API_KEY` bearer secret. Each build runs in its own `sandbox_child.py` process: unprivileged uid, scrubbed environment, resource limits and seccomp. The worker holds no cloud credentials; the API uploads the returned artifacts.
+
+## Configuration
+
+| Variable | Default | Meaning |
+| --- | --- | --- |
+| `API_KEY` | required | shared bearer secret |
+| `MAX_CONCURRENT` | 2 | builds allowed at once |
+| `WARM_POOL` | `MAX_CONCURRENT` | parked children kept ready |
+| `BUILD_TIMEOUT_S` | 60 | wall-clock limit per build |
+| `REQUIRE_SECCOMP` | 1 | refuse to build when seccomp cannot load |
+
+## Run
+
+```bash
+docker build -t cad-forge workers/cad-forge
+docker run --rm -p 8080:8080 -e API_KEY=secret cad-forge
+curl -s -X POST localhost:8080/build -H 'authorization: Bearer secret' \
+ -H 'content-type: application/json' -d '{"code":"result = Box(10, 10, 10)"}'
+```
+
+Tests: `python -m pytest workers/cad-forge`. The caller lives in `api/_lib/cad/`.
diff --git a/workers/cad-forge/cad_policy.py b/workers/cad-forge/cad_policy.py
new file mode 100644
index 000000000..71776bef2
--- /dev/null
+++ b/workers/cad-forge/cad_policy.py
@@ -0,0 +1,176 @@
+"""
+Static policy for model-written build123d programs.
+
+CAD Forge executes Python that a language model wrote from a stranger's prompt,
+so the program is treated as hostile. This module is the first of four layers
+(the others are a seccomp filter, an unprivileged uid, and resource limits; see
+``sandbox_child.py`` and ``main.py``). It parses the source once and refuses
+anything a parametric part has no reason to contain:
+
+ * imports outside ``ALLOWED_MODULES``
+ * any attribute or name that starts with an underscore (``__class__``,
+ ``__globals__``, ``_private``), which is how every classic Python sandbox
+ escape walks from a harmless object to ``os``
+ * the builtins that read files, evaluate strings, or reach into frames
+ * ``str.format`` and friends, whose field syntax (``"{0.__class__}"``) does
+ attribute lookups the AST cannot see
+
+It also supplies the trimmed ``__builtins__`` the program runs under and a
+guarded ``__import__`` that honours the same allowlist at runtime.
+
+Stdlib only, so it can be unit tested without OpenCascade installed.
+"""
+
+from __future__ import annotations
+
+import ast
+import builtins
+import types
+from dataclasses import dataclass
+from typing import Optional
+
+MAX_SOURCE_CHARS = 40_000
+MAX_AST_NODES = 20_000
+
+# Modules a program may import. build123d is the modeling API, bd_warehouse its
+# author's library of standard parts (involute gears, ISO threads, fasteners,
+# bearings); math, itertools and functools cover the arithmetic and iteration
+# real parametric parts use.
+ALLOWED_MODULES = frozenset({"build123d", "bd_warehouse", "math", "itertools", "functools"})
+
+# Modules a program may bind whole (`import math`). The CAD libraries are
+# reachable only through `from ... import Name`, because a bound module object
+# lets a program walk into whatever that library imported (`build123d.exporters.os`).
+WHOLE_IMPORT_MODULES = frozenset({"math", "itertools", "functools"})
+
+# `from X import *` is only safe where X curates __all__.
+STAR_IMPORT_MODULES = frozenset({"build123d"})
+
+BANNED_NAMES = frozenset({
+ "eval", "exec", "compile", "open", "input", "breakpoint", "help",
+ "globals", "locals", "vars", "dir",
+ "getattr", "setattr", "delattr",
+ "exit", "quit", "memoryview", "object", "type",
+ "__import__", "__builtins__", "__loader__", "__spec__",
+})
+
+# Attribute names that perform attribute lookups from inside a string.
+BANNED_ATTRIBUTES = frozenset({"format", "format_map", "vformat", "mro"})
+
+SAFE_BUILTIN_NAMES = (
+ "abs", "all", "any", "bool", "dict", "divmod", "enumerate", "filter",
+ "float", "frozenset", "hasattr", "int", "isinstance", "iter", "len", "list",
+ "map", "max", "min", "next", "pow", "print", "range", "reversed", "round",
+ "set", "slice", "sorted", "str", "sum", "tuple", "zip", "super",
+ "property", "staticmethod", "classmethod",
+ "ArithmeticError", "AssertionError", "Exception", "IndexError", "KeyError",
+ "RuntimeError", "StopIteration", "TypeError", "ValueError",
+ "ZeroDivisionError", "NotImplementedError",
+)
+
+
+@dataclass
+class PolicyViolation(Exception):
+ message: str
+ line: Optional[int] = None
+
+ def __str__(self) -> str:
+ return f"line {self.line}: {self.message}" if self.line else self.message
+
+
+def _top_module(name: str) -> str:
+ return (name or "").split(".", 1)[0]
+
+
+def _private_path(name: str) -> bool:
+ return any(part.startswith("_") for part in (name or "").split("."))
+
+
+def check_source(source: str) -> ast.Module:
+ """Parse and vet a program. Returns the AST or raises PolicyViolation.
+
+ A SyntaxError propagates unchanged so the caller can report it as a syntax
+ problem (with its line) rather than a policy refusal.
+ """
+ if not isinstance(source, str) or not source.strip():
+ raise PolicyViolation("The program is empty.")
+ if len(source) > MAX_SOURCE_CHARS:
+ raise PolicyViolation(f"The program is longer than {MAX_SOURCE_CHARS} characters.")
+
+ tree = ast.parse(source, filename="<design>", mode="exec")
+
+ count = 0
+ for node in ast.walk(tree):
+ count += 1
+ if count > MAX_AST_NODES:
+ raise PolicyViolation("The program is too large to build.")
+ line = getattr(node, "lineno", None)
+
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if _private_path(alias.name):
+ raise PolicyViolation(f"importing '{alias.name}' is not allowed.", line)
+ if _top_module(alias.name) not in ALLOWED_MODULES:
+ raise PolicyViolation(f"import of '{alias.name}' is not allowed; only build123d, bd_warehouse, math, itertools and functools are available.", line)
+ if alias.name not in WHOLE_IMPORT_MODULES:
+ raise PolicyViolation(f"use 'from {alias.name} import ...' instead of 'import {alias.name}'.", line)
+ elif isinstance(node, ast.ImportFrom):
+ if node.level:
+ raise PolicyViolation("relative imports are not allowed.", line)
+ if _private_path(node.module or ""):
+ raise PolicyViolation(f"importing from '{node.module}' is not allowed.", line)
+ if _top_module(node.module or "") not in ALLOWED_MODULES:
+ raise PolicyViolation(f"import from '{node.module}' is not allowed; only build123d, bd_warehouse, math, itertools and functools are available.", line)
+ for alias in node.names:
+ if alias.name == "*" and node.module not in STAR_IMPORT_MODULES:
+ raise PolicyViolation(f"'from {node.module} import *' is not allowed; import the names you use.", line)
+ if alias.name != "*" and alias.name.startswith("_"):
+ raise PolicyViolation(f"importing '{alias.name}' is not allowed.", line)
+ elif isinstance(node, ast.Attribute):
+ if node.attr.startswith("_"):
+ raise PolicyViolation(f"access to '.{node.attr}' is not allowed.", line)
+ if node.attr in BANNED_ATTRIBUTES:
+ raise PolicyViolation(f"'.{node.attr}' is not available; use an f-string instead.", line)
+ elif isinstance(node, ast.Name):
+ if node.id in BANNED_NAMES:
+ raise PolicyViolation(f"'{node.id}' is not available in a CAD program.", line)
+ if node.id.startswith("__"):
+ raise PolicyViolation(f"the name '{node.id}' is not allowed.", line)
+ elif isinstance(node, (ast.AsyncFunctionDef, ast.Await, ast.AsyncFor, ast.AsyncWith)):
+ raise PolicyViolation("async code is not allowed.", line)
+ elif isinstance(node, (ast.FunctionDef, ast.ClassDef)):
+ if node.name.startswith("__"):
+ raise PolicyViolation(f"defining '{node.name}' is not allowed.", line)
+ elif isinstance(node, ast.arg):
+ if node.arg.startswith("__"):
+ raise PolicyViolation(f"the argument name '{node.arg}' is not allowed.", line)
+ elif isinstance(node, ast.keyword):
+ if node.arg and node.arg.startswith("__"):
+ raise PolicyViolation(f"the keyword '{node.arg}' is not allowed.", line)
+ return tree
+
+
+def guarded_import(name, globals=None, locals=None, fromlist=(), level=0):
+ """``__import__`` for the program namespace: allowlisted modules only."""
+ if level or _private_path(name) or _top_module(name) not in ALLOWED_MODULES:
+ raise ImportError(f"import of '{name}' is not allowed")
+ if not fromlist and name not in WHOLE_IMPORT_MODULES:
+ raise ImportError(f"use 'from {name} import ...' instead of 'import {name}'")
+ for item in fromlist or ():
+ if item == "*" and name not in STAR_IMPORT_MODULES:
+ raise ImportError(f"'from {name} import *' is not allowed")
+ if item != "*" and str(item).startswith("_"):
+ raise ImportError(f"importing '{item}' is not allowed")
+ module = builtins.__import__(name, globals, locals, fromlist, level)
+ for item in fromlist or ():
+ if item != "*" and isinstance(getattr(module, item, None), types.ModuleType):
+ raise ImportError(f"'{item}' is a module; import the names you use from it")
+ return module
+
+
+def safe_builtins() -> dict:
+ table = {name: getattr(builtins, name) for name in SAFE_BUILTIN_NAMES}
+ table["__import__"] = guarded_import
+ # `class` statements resolve this name; without it a helper class fails.
+ table["__build_class__"] = builtins.__build_class__
+ return table
diff --git a/workers/cad-forge/main.py b/workers/cad-forge/main.py
new file mode 100644
index 000000000..e6734a53b
--- /dev/null
+++ b/workers/cad-forge/main.py
@@ -0,0 +1,317 @@
+"""
+CAD Forge worker: builds a build123d program into a real B-rep part.
+
+API contract:
+ POST /build { code: str }
+ → 200 { ok: true, metrics, artifacts: { step, stl, glb, thumb_svg?, drawing_svg? }, log, elapsed_s }
+ → 200 { ok: false, error: { kind, message, line }, log, elapsed_s }
+ Artifacts are base64. A program that fails is still a 200: the failure is
+ the program's, and the caller (api/cad.js) feeds it back to the model for
+ a repair round. Non-200 means the worker itself could not run the build.
+
+ GET /health → { ok, warm, max_concurrent, seccomp_required, build123d }
+
+Every build runs in its own sandbox_child.py process: parked warm (build123d
+already imported), unprivileged uid, scrubbed env, resource limits, seccomp,
+then exits. The worker holds no cloud credentials: artifacts return inline and
+the API uploads them.
+
+Environment variables:
+ API_KEY shared bearer secret (required)
+ MAX_CONCURRENT builds allowed at once (default: 2)
+ WARM_POOL parked children kept ready (default: MAX_CONCURRENT)
+ BUILD_TIMEOUT_S wall-clock limit per build (default: 60)
+ REQUIRE_SECCOMP refuse to build when seccomp cannot load (default: 1)
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import json
+import logging
+import os
+import re
+import resource
+import signal
+import shutil
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from importlib import metadata
+from typing import Optional
+
+from fastapi import FastAPI, Header, HTTPException
+from pydantic import BaseModel, Field
+
+from cad_policy import MAX_SOURCE_CHARS
+from worker_security import require_api_key
+
+logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
+log = logging.getLogger("cad-forge")
+
+API_KEY = os.environ.get("API_KEY", "")
+MAX_CONCURRENT = max(1, int(os.environ.get("MAX_CONCURRENT", "2")))
+WARM_POOL = max(1, int(os.environ.get("WARM_POOL", str(MAX_CONCURRENT))))
+BUILD_TIMEOUT_S = float(os.environ.get("BUILD_TIMEOUT_S", "60"))
+REQUIRE_SECCOMP = os.environ.get("REQUIRE_SECCOMP", "1") != "0"
+
+CHILD = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_child.py")
+SANDBOX_UID = 65534 # nobody
+MEMORY_LIMIT_BYTES = int(os.environ.get("SANDBOX_MEMORY_MB", "3072")) * 1024 * 1024
+CPU_LIMIT_S = int(BUILD_TIMEOUT_S * 2)
+MAX_ARTIFACT_BYTES = 24 * 1024 * 1024
+ARTIFACT_KEYS = {
+ "part.step": "step",
+ "part.stl": "stl",
+ "part.glb": "glb",
+ "thumb.svg": "thumb_svg",
+ "drawing.svg": "drawing_svg",
+}
+
+
+def _limits() -> None:
+ """preexec_fn: hard ceilings the program cannot raise."""
+ resource.setrlimit(resource.RLIMIT_AS, (MEMORY_LIMIT_BYTES, MEMORY_LIMIT_BYTES))
+ resource.setrlimit(resource.RLIMIT_CPU, (CPU_LIMIT_S, CPU_LIMIT_S))
+ resource.setrlimit(resource.RLIMIT_FSIZE, (64 * 1024 * 1024, 64 * 1024 * 1024))
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
+ resource.setrlimit(resource.RLIMIT_NOFILE, (256, 256))
+ os.setsid()
+
+
+@dataclass
+class Child:
+ proc: subprocess.Popen
+ workdir: str
+ started: float
+
+
+def _spawn() -> Child:
+ workdir = tempfile.mkdtemp(prefix="cad-")
+ drop = os.geteuid() == 0
+ if drop:
+ os.chown(workdir, SANDBOX_UID, SANDBOX_UID)
+ env = {
+ "PATH": "/usr/local/bin:/usr/bin:/bin",
+ "HOME": workdir,
+ "TMPDIR": workdir,
+ # OpenBLAS (pulled in through scipy) otherwise starts one thread per
+ # host core, and 32 thread stacks blow straight through RLIMIT_AS.
+ "OMP_NUM_THREADS": "2",
+ "OPENBLAS_NUM_THREADS": "2",
+ "PYTHONDONTWRITEBYTECODE": "1",
+ }
+ proc = subprocess.Popen(
+ [sys.executable, "-I", CHILD],
+ cwd=workdir,
+ env=env,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ close_fds=True,
+ preexec_fn=_limits,
+ user=SANDBOX_UID if drop else None,
+ group=SANDBOX_UID if drop else None,
+ extra_groups=[] if drop else None,
+ )
+ return Child(proc=proc, workdir=workdir, started=time.monotonic())
+
+
+def _discard(child: Child) -> None:
+ if child.proc.poll() is None:
+ child.proc.kill()
+ try:
+ child.proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ log.error("sandbox child %s did not exit after kill", child.proc.pid)
+ for stream in (child.proc.stdin, child.proc.stdout, child.proc.stderr):
+ if stream and not stream.closed:
+ stream.close()
+ shutil.rmtree(child.workdir, ignore_errors=True)
+
+
+class WarmPool:
+ """Children that have finished importing build123d and wait for one job."""
+
+ def __init__(self, size: int):
+ self.size = size
+ self._ready: list[Child] = []
+ self._lock = threading.Lock()
+
+ def _await_ready(self, child: Child) -> bool:
+ line = child.proc.stdout.readline()
+ if line.strip() == b"READY":
+ return True
+ err = child.proc.stderr.read().decode("utf-8", "replace")[-2000:] if child.proc.poll() is not None else ""
+ log.error("sandbox child failed to start: %s", err or line[:200])
+ _discard(child)
+ return False
+
+ def refill(self) -> None:
+ while True:
+ with self._lock:
+ if len(self._ready) >= self.size:
+ return
+ child = _spawn()
+ if not self._await_ready(child):
+ return
+ with self._lock:
+ self._ready.append(child)
+
+ def take(self) -> Child:
+ with self._lock:
+ child = self._ready.pop(0) if self._ready else None
+ if child is None or child.proc.poll() is not None:
+ if child is not None:
+ _discard(child)
+ child = _spawn()
+ if not self._await_ready(child):
+ raise RuntimeError("sandbox child failed to start")
+ threading.Thread(target=self.refill, daemon=True).start()
+ return child
+
+ def warm(self) -> int:
+ with self._lock:
+ return sum(1 for c in self._ready if c.proc.poll() is None)
+
+ def close(self) -> None:
+ with self._lock:
+ children, self._ready = self._ready, []
+ for child in children:
+ _discard(child)
+
+
+pool = WarmPool(WARM_POOL)
+_slots = asyncio.Semaphore(MAX_CONCURRENT)
+
+
+CRASH_LINE = re.compile(r'File "<design>", line (\d+)')
+
+
+def _signal_failure(returncode: int, stderr: str) -> dict:
+ """Explain a child that died before reporting, by the signal that killed it."""
+ signum = -returncode if returncode and returncode < 0 else None
+ match = CRASH_LINE.findall(stderr or "")
+ line = int(match[-1]) if match else None
+ if signum == signal.SIGXCPU:
+ return {"kind": "timeout", "message": "The design used more CPU time than a build allows. Reduce feature counts or boolean operations.", "line": line}
+ if signum in (signal.SIGKILL, signal.SIGABRT):
+ return {"kind": "memory", "message": "The build process was stopped by its memory limit. Simplify the geometry.", "line": line}
+ where = f" while running line {line}" if line else ""
+ return {"kind": "crash", "message": f"The geometry kernel crashed{where}. That operation received geometry it cannot handle; build that feature a different way.", "line": line}
+
+
+def _collect(child: Child, result: dict) -> dict:
+ if not result.get("ok"):
+ return result
+ artifacts = {}
+ total = 0
+ for name in result.get("files", []):
+ path = os.path.join(child.workdir, name)
+ if name not in ARTIFACT_KEYS or not os.path.isfile(path):
+ continue
+ total += os.path.getsize(path)
+ if total > MAX_ARTIFACT_BYTES:
+ return {
+ "ok": False,
+ "error": {"kind": "export", "message": "The exported files exceed 24 MB. Reduce detail such as fine fillets, text, or thread pitch.", "line": None},
+ "log": result.get("log", ""),
+ "elapsed_s": result.get("elapsed_s"),
+ }
+ with open(path, "rb") as fh:
+ artifacts[ARTIFACT_KEYS[name]] = base64.b64encode(fh.read()).decode("ascii")
+ result["artifacts"] = artifacts
+ result.pop("files", None)
+ return result
+
+
+def _read_result(child: Child) -> Optional[dict]:
+ path = os.path.join(child.workdir, "result.json")
+ if not os.path.exists(path):
+ return None
+ with open(path, "r", encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def run_build(code: str) -> dict:
+ child = pool.take()
+ started = time.perf_counter()
+ try:
+ job = json.dumps({"code": code, "require_seccomp": REQUIRE_SECCOMP}) + "\n"
+ try:
+ _, stderr = child.proc.communicate(job.encode("utf-8"), timeout=BUILD_TIMEOUT_S)
+ except subprocess.TimeoutExpired:
+ child.proc.kill()
+ # The part is reported before its drawings, so a build that timed
+ # out while projecting views still has a complete part to return.
+ result = _read_result(child)
+ if result and result.get("ok"):
+ result["drawings_skipped"] = True
+ return _collect(child, result)
+ return {
+ "ok": False,
+ "error": {"kind": "timeout", "message": f"The design took longer than {int(BUILD_TIMEOUT_S)} s to build. Reduce feature counts or boolean operations.", "line": None},
+ "log": "",
+ "elapsed_s": round(time.perf_counter() - started, 3),
+ }
+ result = _read_result(child)
+ if result is None:
+ text = stderr.decode("utf-8", "replace")
+ log.warning("sandbox child exited %s without a result: %s", child.proc.returncode, text[-800:])
+ return {
+ "ok": False,
+ "error": _signal_failure(child.proc.returncode, text),
+ "log": "",
+ "elapsed_s": round(time.perf_counter() - started, 3),
+ }
+ return _collect(child, result)
+ finally:
+ _discard(child)
+
+
+@asynccontextmanager
+async def lifespan(_app: FastAPI):
+ threading.Thread(target=pool.refill, daemon=True).start()
+ yield
+ pool.close()
+
+
+app = FastAPI(title="three.ws CAD Forge", lifespan=lifespan)
+
+
+class BuildRequest(BaseModel):
+ code: str = Field(..., min_length=1, max_length=MAX_SOURCE_CHARS)
+
+
+def _auth(authorization: Optional[str]) -> None:
+ try:
+ require_api_key(authorization, API_KEY)
+ except PermissionError as exc:
+ raise HTTPException(status_code=401, detail=str(exc)) from None
+
+
+def health():
+ return {
+ "ok": True,
+ "warm": pool.warm(),
+ "max_concurrent": MAX_CONCURRENT,
+ "seccomp_required": REQUIRE_SECCOMP,
+ "build123d": metadata.version("build123d"),
+ }
+
+
+async def build(req: BuildRequest, authorization: Optional[str] = Header(default=None)):
+ _auth(authorization)
+ async with _slots:
+ try:
+ return await asyncio.to_thread(run_build, req.code)
+ except RuntimeError as exc:
+ log.error("build could not start: %s", exc)
+ raise HTTPException(status_code=503, detail="The CAD sandbox is starting. Retry in a few seconds.") from None
diff --git a/workers/cad-forge/requirements.txt b/workers/cad-forge/requirements.txt
new file mode 100644
index 000000000..acc2ead08
--- /dev/null
+++ b/workers/cad-forge/requirements.txt
@@ -0,0 +1,16 @@
+fastapi==0.115.5
+uvicorn[standard]==0.32.1
+pydantic==2.10.3
+# worker_security.py (vendored) imports httpx.
+httpx==0.27.2
+# build123d 0.13 on OpenCascade 8 (cadquery-ocp-novtk wheels): the same
+# modeling layer text-to-cad's cadgen uses, so a design's source runs unchanged
+# in either. Pinned so a kernel upgrade is a deliberate change, not a rebuild.
+build123d==0.13.0
+# Standard parts by build123d's author (Apache-2.0): involute gears, ISO
+# threads, fasteners, bearings. Programs import from it by name.
+bd_warehouse==0.4.0
+# ctypes binding to libseccomp: denies sockets, exec and fork to the program.
+pyseccomp==0.1.2
+cadquery-ocp-novtk==8.0.1.1.0
+numpy==2.4.6
diff --git a/workers/cad-forge/sandbox_child.py b/workers/cad-forge/sandbox_child.py
new file mode 100644
index 000000000..788c697d2
--- /dev/null
+++ b/workers/cad-forge/sandbox_child.py
@@ -0,0 +1,390 @@
+"""
+One-shot sandbox process for a single CAD build.
+
+The parent (main.py) spawns this as an unprivileged uid with a scrubbed
+environment and hard resource limits, then keeps it parked: it imports
+build123d (about 2.5 s of OpenCascade loading) and blocks on stdin, so the cost
+is paid before a request arrives. When a job lands it:
+
+ 1. installs a seccomp filter: no sockets, no exec, no fork (threads stay
+ allowed, OpenCascade meshes in parallel)
+ 2. vets the program with cad_policy and runs it under trimmed builtins
+ 3. resolves the program's ``result`` into one solid shape
+ 4. writes part.step, part.stl, part.glb, thumb.svg and drawing.svg into its
+ working directory, plus result.json with the measurements
+
+then exits. A process never runs a second program, so nothing one design does
+can leak into the next.
+"""
+
+from __future__ import annotations
+
+import errno
+import faulthandler
+import io
+import json
+import math
+import os
+import sys
+import time
+import traceback
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+import build123d as bd # noqa: E402 (warm import is the point of this process)
+from build123d import ( # noqa: E402
+ BuildPart, BuildSketch, BuildLine, Color, Compound, ExportSVG, LineType, Shape, Solid, Unit,
+ export_gltf, export_step, export_stl,
+)
+
+from cad_policy import PolicyViolation, check_source, safe_builtins # noqa: E402
+
+MAX_LOG_CHARS = 4_000
+MAX_EXTENT_MM = 5_000.0
+MIN_VOLUME_MM3 = 1e-6
+DEFAULT_COLOR = (0.70, 0.74, 0.80)
+CLONE_THREAD = 0x00010000
+
+SECCOMP_DENY = (
+ "socket", "socketpair", "connect", "bind", "listen", "accept", "accept4",
+ "execve", "execveat", "fork", "vfork", "ptrace", "process_vm_readv",
+ "process_vm_writev", "unshare", "setns", "mount", "umount2", "pivot_root",
+ "chroot", "keyctl", "add_key", "request_key", "bpf", "perf_event_open",
+ "userfaultfd", "personality", "kexec_load", "init_module", "finit_module",
+)
+
+
+# Edge treatments the kernel rejected and the smaller size that built instead.
+ADJUSTMENTS: list[str] = []
+EDGE_OP_SCALES = (0.5, 0.25)
+
+
+def _unchanged_target(op_name: str, objects):
+ """The shape a skipped edge treatment leaves behind, resolved the way
+ build123d's own fillet/chamfer resolve their target: the active builder's
+ part, else the part the selected edges came from."""
+ from build123d.build_common import Builder
+
+ context = Builder._get_context(op_name)
+ if context is not None:
+ return getattr(context, "_obj", None)
+ if isinstance(objects, Shape):
+ items = [objects]
+ else:
+ try:
+ items = list(objects or [])
+ except TypeError:
+ return None
+ return getattr(items[0], "topo_parent", None) if items else None
+
+
+def _forgiving(op, size_kw: str):
+ """Wrap fillet/chamfer: when the kernel rejects a size, retry smaller.
+
+ A rejected fillet is the most common reason a valid design fails, and the
+ kernel's own advice is "try a smaller value". Halving, then quartering, is
+ that advice applied. When no size builds, the edges are left sharp: a
+ cosmetic round is never worth failing a part over. Every reduction or skip
+ is reported to the user next to the design.
+ """
+
+ def wrapper(*args, **kwargs):
+ try:
+ return op(*args, **kwargs)
+ except Exception as original: # noqa: BLE001 (OCCT raises several unrelated types)
+ in_kwargs = size_kw in kwargs
+ size = kwargs.get(size_kw) if in_kwargs else (args[1] if len(args) > 1 else None)
+ if isinstance(size, bool) or not isinstance(size, (int, float)) or size <= 0:
+ raise
+ for scale in EDGE_OP_SCALES:
+ smaller = size * scale
+ try:
+ if in_kwargs:
+ out = op(*args, **{**kwargs, size_kw: smaller})
+ else:
+ out = op(args[0], smaller, *args[2:], **kwargs)
+ except Exception: # noqa: BLE001
+ continue
+ ADJUSTMENTS.append(f"{op.__name__} {size:g} mm could not be built; used {smaller:g} mm")
+ return out
+ unchanged = _unchanged_target(op.__name__, args[0] if args else kwargs.get("objects"))
+ if unchanged is None:
+ raise original
+ ADJUSTMENTS.append(f"{op.__name__} {size:g} mm could not be built at any size; left the edges sharp")
+ return unchanged
+
+ wrapper.__name__ = op.__name__
+ wrapper.__doc__ = op.__doc__
+ return wrapper
+
+
+bd.fillet = _forgiving(bd.fillet, "radius")
+bd.chamfer = _forgiving(bd.chamfer, "length")
+
+
+class BuildFailure(Exception):
+ def __init__(self, kind: str, message: str, line: int | None = None):
+ super().__init__(message)
+ self.kind = kind
+ self.message = message
+ self.line = line
+
+
+def install_seccomp() -> bool:
+ """Deny network, exec and process creation for the rest of this process.
+
+ Returns False when the kernel or runtime refuses seccomp (some local Docker
+ setups); production refuses to build without it, see main.REQUIRE_SECCOMP.
+ """
+ try:
+ import pyseccomp as seccomp
+ except ImportError:
+ return False
+ try:
+ flt = seccomp.SyscallFilter(seccomp.ALLOW)
+ for name in SECCOMP_DENY:
+ try:
+ flt.add_rule(seccomp.ERRNO(errno.EPERM), name)
+ except (ValueError, RuntimeError, OSError):
+ continue
+ # clone3 passes its flags in a struct seccomp cannot inspect; ENOSYS makes
+ # glibc fall back to clone, whose flags we can: threads yes, processes no.
+ try:
+ flt.add_rule(seccomp.ERRNO(errno.ENOSYS), "clone3")
+ except (ValueError, RuntimeError, OSError):
+ pass
+ flt.add_rule(seccomp.ERRNO(errno.EPERM), "clone", seccomp.Arg(0, seccomp.MASKED_EQ, CLONE_THREAD, 0))
+ flt.load()
+ return True
+ except Exception: # noqa: BLE001 (any failure means "not sandboxed", reported upstream)
+ return False
+
+
+def design_line(exc: BaseException) -> int | None:
+ line = None
+ for frame in traceback.extract_tb(exc.__traceback__):
+ if frame.filename == "<design>":
+ line = frame.lineno
+ return line
+
+
+def run_program(source: str, log: io.StringIO) -> object:
+ try:
+ tree = check_source(source)
+ except SyntaxError as exc:
+ raise BuildFailure("syntax", f"{exc.msg}", exc.lineno) from None
+ except PolicyViolation as exc:
+ raise BuildFailure("policy", exc.message, exc.line) from None
+
+ code = compile(tree, "<design>", "exec")
+ namespace = {"__builtins__": safe_builtins(), "__name__": "__design__"}
+ real_stdout = sys.stdout
+ sys.stdout = log
+ try:
+ exec(code, namespace) # noqa: S102 (vetted program, sandboxed process)
+ except BuildFailure:
+ raise
+ except MemoryError:
+ raise BuildFailure("memory", "The design ran out of memory. Simplify the geometry.") from None
+ except RecursionError:
+ raise BuildFailure("runtime", "The design recursed too deeply.", None) from None
+ except Exception as exc: # noqa: BLE001 (the program's own error, reported with its line)
+ message = f"{type(exc).__name__}: {exc}".strip()
+ raise BuildFailure("runtime", message[:600], design_line(exc)) from None
+ finally:
+ sys.stdout = real_stdout
+ return namespace
+
+
+def resolve_result(namespace: dict) -> Shape:
+ if "result" not in namespace:
+ builders = [v for v in namespace.values() if isinstance(v, BuildPart)]
+ if len(builders) == 1:
+ namespace["result"] = builders[0]
+ else:
+ raise BuildFailure("result", "The program never assigned the finished shape to a variable named `result`.")
+ value = namespace["result"]
+ if isinstance(value, BuildPart):
+ value = value.part
+ if isinstance(value, (BuildSketch, BuildLine)):
+ raise BuildFailure("result", "`result` is a 2D sketch. Extrude or revolve it into a solid.")
+ if isinstance(value, (list, tuple)):
+ shapes = [v.part if isinstance(v, BuildPart) else v for v in value]
+ if not shapes or not all(isinstance(s, Shape) for s in shapes):
+ raise BuildFailure("result", "`result` is a list that does not contain only shapes.")
+ value = Compound(children=shapes)
+ if not isinstance(value, Shape):
+ raise BuildFailure("result", f"`result` must be a build123d shape, got {type(value).__name__}.")
+ if not value.solids():
+ raise BuildFailure("result", "`result` has no solid volume. Build a 3D part, not a surface or a wire.")
+ return value
+
+
+def measure(shape: Shape) -> dict:
+ box = shape.bounding_box()
+ size = (box.size.X, box.size.Y, box.size.Z)
+ if not all(math.isfinite(v) for v in size):
+ raise BuildFailure("result", "The part has an infinite or undefined extent.")
+ if max(size) > MAX_EXTENT_MM:
+ raise BuildFailure("result", f"The part is {max(size):.0f} mm across; the limit is {MAX_EXTENT_MM:.0f} mm.")
+ volume = float(shape.volume)
+ if volume < MIN_VOLUME_MM3:
+ raise BuildFailure("result", "The part has no volume.")
+ center = shape.center()
+ return {
+ "size_mm": [round(v, 4) for v in size],
+ "min_mm": [round(box.min.X, 4), round(box.min.Y, 4), round(box.min.Z, 4)],
+ "volume_mm3": round(volume, 4),
+ "area_mm2": round(float(shape.area), 4),
+ "center_mm": [round(center.X, 4), round(center.Y, 4), round(center.Z, 4)],
+ "solids": len(shape.solids()),
+ "faces": len(shape.faces()),
+ "edges": len(shape.edges()),
+ "valid": bool(shape.is_valid),
+ }
+
+
+def _project(shape: Shape, origin, up):
+ visible, hidden = shape.project_to_viewport(origin, up, (0, 0, 0))
+ return Compound(children=list(visible)), Compound(children=list(hidden))
+
+
+def write_thumbnail(shape: Shape, path: str) -> None:
+ centered = shape.moved(bd.Location(-shape.center()))
+ extent = max(centered.bounding_box().size.X, centered.bounding_box().size.Y, centered.bounding_box().size.Z) or 1.0
+ distance = extent * 6
+ visible, hidden = _project(centered, (distance, -distance, distance * 0.8), (0, 0, 1))
+ svg = ExportSVG(scale=100.0 / extent, margin=4)
+ svg.add_layer("hidden", line_color=(150, 160, 175), line_type=LineType.ISO_DOT, line_weight=0.2)
+ svg.add_layer("visible", line_color=(20, 24, 32), line_weight=0.45)
+ if hidden.edges():
+ svg.add_shape(hidden, layer="hidden")
+ svg.add_shape(visible, layer="visible")
+ svg.write(path)
+
+
+def write_drawing(shape: Shape, size_mm, path: str) -> None:
+ """Third-angle sheet: front, top and right orthographic views plus an iso."""
+ centered = shape.moved(bd.Location(-shape.center()))
+ extent = max(size_mm) or 1.0
+ d = extent * 6
+ views = [
+ ("FRONT", (0, -d, 0), (0, 0, 1), (0, 0)),
+ ("RIGHT", (d, 0, 0), (0, 0, 1), (1, 0)),
+ ("TOP", (0, 0, d), (0, 1, 0), (0, 1)),
+ ("ISOMETRIC", (d, -d, d * 0.8), (0, 0, 1), (1, 1)),
+ ]
+ cell = extent * 1.6
+ svg = ExportSVG(scale=180.0 / (cell * 2), margin=6)
+ svg.add_layer("hidden", line_color=(150, 160, 175), line_type=LineType.ISO_DASH, line_weight=0.18)
+ svg.add_layer("visible", line_color=(20, 24, 32), line_weight=0.4)
+ labels = []
+ for name, origin, up, (col, row) in views:
+ visible, hidden = _project(centered, origin, up)
+ offset = bd.Location((col * cell, -row * cell, 0))
+ if hidden.edges():
+ svg.add_shape(hidden.moved(offset), layer="hidden")
+ svg.add_shape(visible.moved(offset), layer="visible")
+ labels.append((name, col * cell, -row * cell - cell * 0.42))
+ svg.write(path)
+
+ # View captions in drawing units. ExportSVG flips Y with scale(1,-1), so each
+ # caption is placed at -y inside an un-flipped group.
+ with open(path, "r", encoding="utf-8") as fh:
+ text = fh.read()
+ font = cell * 0.055
+ captions = "".join(
+ f'<text x="{x:.3f}" y="{-y:.3f}" font-family="ui-monospace, Menlo, monospace" '
+ f'font-size="{font:.3f}" fill="rgb(90,100,115)" text-anchor="middle">{name}</text>'
+ for name, x, y in labels
+ )
+ dims = " x ".join(f"{v:.2f}" for v in size_mm)
+ captions += (
+ f'<text x="{cell * 0.5:.3f}" y="{cell * 1.62:.3f}" font-family="ui-monospace, Menlo, monospace" '
+ f'font-size="{font * 0.9:.3f}" fill="rgb(90,100,115)" text-anchor="middle">'
+ f"OVERALL {dims} mm | three.ws CAD Forge</text>"
+ )
+ text = text.replace("</svg>", f'<g transform="scale(1,-1)"><g transform="scale(1,-1)">{captions}</g></g></svg>', 1)
+ with open(path, "w", encoding="utf-8") as fh:
+ fh.write(text)
+
+
+def export_part(shape: Shape, metrics: dict) -> dict:
+ if getattr(shape, "color", None) is None:
+ shape.color = Color(*DEFAULT_COLOR)
+ timings = {}
+ t = time.perf_counter()
+ export_step(shape, "part.step", unit=Unit.MM)
+ timings["step"] = time.perf_counter() - t
+ # Deflection scales with the part so a 5 mm clip and a 2 m frame both mesh
+ # smoothly without the large part exploding into millions of triangles.
+ deflection = max(0.005, max(metrics["size_mm"]) / 1500.0)
+ t = time.perf_counter()
+ export_stl(shape, "part.stl", tolerance=deflection, angular_tolerance=0.15)
+ export_gltf(shape, "part.glb", unit=Unit.MM, binary=True, linear_deflection=deflection, angular_deflection=0.15)
+ timings["mesh"] = time.perf_counter() - t
+ return {"files": ["part.step", "part.stl", "part.glb"], "timings_s": {k: round(v, 3) for k, v in timings.items()}}
+
+
+def export_drawings(shape: Shape, metrics: dict) -> list[str]:
+ """Hidden-line views. Optional: the part is already reported before this
+ runs, so a slow or failing projection only costs the drawings."""
+ try:
+ write_thumbnail(shape, "thumb.svg")
+ write_drawing(shape, metrics["size_mm"], "drawing.svg")
+ return ["thumb.svg", "drawing.svg"]
+ except Exception: # noqa: BLE001 (hidden-line removal can fail on exotic B-reps; the part itself is fine)
+ for leftover in ("thumb.svg", "drawing.svg"):
+ if os.path.exists(leftover):
+ os.remove(leftover)
+ return []
+
+
+def write_result(out: dict) -> None:
+ tmp = "result.json.tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(out, fh)
+ os.replace(tmp, "result.json")
+
+
+def main() -> int:
+ # A segfault inside OpenCascade prints the Python stack to stderr, which is
+ # how the parent learns which program line crashed the kernel.
+ faulthandler.enable(file=sys.stderr, all_threads=False)
+ sys.stdout.write("READY\n")
+ sys.stdout.flush()
+ raw = sys.stdin.readline()
+ started = time.perf_counter()
+ log = io.StringIO()
+ shape = None
+ out: dict
+ try:
+ job = json.loads(raw or "{}")
+ sandboxed = install_seccomp()
+ if job.get("require_seccomp") and not sandboxed:
+ raise BuildFailure("sandbox", "The build sandbox could not be established.")
+ namespace = run_program(str(job.get("code") or ""), log)
+ shape = resolve_result(namespace)
+ metrics = measure(shape)
+ exported = export_part(shape, metrics)
+ out = {"ok": True, "metrics": metrics, "seccomp": sandboxed, "adjustments": ADJUSTMENTS[:20], **exported}
+ except BuildFailure as exc:
+ out = {"ok": False, "error": {"kind": exc.kind, "message": exc.message, "line": exc.line}}
+ except MemoryError:
+ out = {"ok": False, "error": {"kind": "memory", "message": "The design ran out of memory. Simplify the geometry.", "line": None}}
+ except Exception as exc: # noqa: BLE001 (export or measurement fault on a valid program)
+ out = {"ok": False, "error": {"kind": "export", "message": f"{type(exc).__name__}: {exc}"[:600], "line": None}}
+ out["log"] = log.getvalue()[-MAX_LOG_CHARS:]
+ out["elapsed_s"] = round(time.perf_counter() - started, 3)
+ write_result(out)
+ if out["ok"]:
+ t = time.perf_counter()
+ out["files"] += export_drawings(shape, out["metrics"])
+ out["timings_s"]["drawing"] = round(time.perf_counter() - t, 3)
+ out["elapsed_s"] = round(time.perf_counter() - started, 3)
+ write_result(out)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/workers/cad-forge/test_cad_policy.py b/workers/cad-forge/test_cad_policy.py
new file mode 100644
index 000000000..96e066cf8
--- /dev/null
+++ b/workers/cad-forge/test_cad_policy.py
@@ -0,0 +1,108 @@
+"""Unit tests for cad_policy. Stdlib only: `python test_cad_policy.py`."""
+
+import unittest
+
+from cad_policy import PolicyViolation, check_source, guarded_import, safe_builtins
+
+GOOD = """
+from build123d import *
+import math
+
+WIDTH = 60 # Width [20..200 mm]
+HOLE = 4 # Hole diameter [2..10 mm]
+
+def ring(r):
+ return Cylinder(r, 5) - Cylinder(r - 2, 5)
+
+with BuildPart() as bracket:
+ Box(WIDTH, 40, 8)
+ fillet(bracket.edges().filter_by(Axis.Z), radius=4)
+ with GridLocations(WIDTH - 15, 25, 2, 2):
+ Hole(HOLE / 2)
+
+result = bracket.part + ring(10).moved(Location((0, 0, 8)))
+label = f"{WIDTH} mm bracket, {math.pi:.2f}"
+"""
+
+
+class PolicyTests(unittest.TestCase):
+ def test_accepts_a_real_parametric_part(self):
+ check_source(GOOD)
+
+ def assertRefused(self, source, fragment=""):
+ with self.assertRaises(PolicyViolation) as ctx:
+ check_source(source)
+ self.assertIn(fragment, str(ctx.exception))
+
+ def test_refuses_foreign_imports(self):
+ self.assertRefused("import os", "import of 'os'")
+ self.assertRefused("import subprocess as s", "subprocess")
+ self.assertRefused("from socket import socket", "socket")
+ self.assertRefused("import build123d.topology._private", "_private")
+ self.assertRefused("from build123d._internal import x", "_internal")
+ self.assertRefused("from . import x", "relative")
+
+ def test_cad_libraries_only_through_from_imports(self):
+ self.assertRefused("import build123d", "from build123d import")
+ self.assertRefused("import build123d as bd", "from build123d import")
+ self.assertRefused("import bd_warehouse.gear", "from bd_warehouse.gear import")
+ self.assertRefused("from bd_warehouse.gear import *", "import *")
+ check_source("from bd_warehouse.gear import SpurGear\nimport math\n")
+
+ def test_runtime_guard_refuses_module_objects(self):
+ with self.assertRaises(ImportError):
+ guarded_import("math", fromlist=("*",))
+ with self.assertRaises(ImportError):
+ guarded_import("build123d")
+ with self.assertRaises(ImportError):
+ guarded_import("os.path", fromlist=("join",))
+
+ def test_refuses_private_imports_from_allowed_modules(self):
+ self.assertRefused("from build123d import _private", "_private")
+
+ def test_refuses_dunder_walks(self):
+ self.assertRefused("x = ().__class__.__base__.__subclasses__()", "is not allowed")
+ self.assertRefused("f = (lambda: 0).__globals__", "__globals__")
+ self.assertRefused("y = Box._private", "_private")
+
+ def test_refuses_dangerous_builtins(self):
+ for name in ("eval", "exec", "open", "compile", "getattr", "globals", "vars", "__import__", "type", "object"):
+ self.assertRefused(f"{name}('x')", name)
+
+ def test_refuses_string_format_attribute_lookups(self):
+ self.assertRefused("s = '{0.__class__}'.format(1)", "format")
+ self.assertRefused("s = '{a}'.format_map({})", "format_map")
+
+ def test_refuses_dunder_definitions_and_names(self):
+ self.assertRefused("def __init__(self): pass", "__init__")
+ self.assertRefused("__builtins__", "__builtins__")
+ self.assertRefused("def f(__x): pass", "__x")
+
+ def test_refuses_async(self):
+ self.assertRefused("async def f():\n pass", "async")
+
+ def test_syntax_errors_propagate_with_a_line(self):
+ with self.assertRaises(SyntaxError) as ctx:
+ check_source("x = (\n")
+ self.assertTrue(ctx.exception.lineno)
+
+ def test_refuses_empty_and_oversized(self):
+ self.assertRefused(" ", "empty")
+ self.assertRefused("x = 1\n" * 10_000, "longer")
+
+ def test_runtime_import_guard(self):
+ self.assertIs(guarded_import("math"), __import__("math"))
+ with self.assertRaises(ImportError):
+ guarded_import("os")
+ with self.assertRaises(ImportError):
+ guarded_import("math", fromlist=("_private",))
+
+ def test_safe_builtins_exclude_escape_hatches(self):
+ table = safe_builtins()
+ for name in ("open", "eval", "exec", "getattr", "__loader__", "compile", "globals"):
+ self.assertNotIn(name, table)
+ self.assertIs(table["__import__"], guarded_import)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=1)
diff --git a/workers/cad-forge/test_sandbox.py b/workers/cad-forge/test_sandbox.py
new file mode 100644
index 000000000..ddda9a4b6
--- /dev/null
+++ b/workers/cad-forge/test_sandbox.py
@@ -0,0 +1,242 @@
+"""
+Integration gate for the CAD sandbox: real builds through the warm pool and
+real escape attempts against each isolation layer. Runs in the Docker build
+(as root, like Cloud Run) and needs build123d installed.
+
+ python test_sandbox.py
+"""
+
+import base64
+import os
+import subprocess
+import sys
+import textwrap
+import unittest
+
+os.environ.setdefault("API_KEY", "build-gate")
+os.environ["BUILD_TIMEOUT_S"] = "10"
+
+import main # noqa: E402
+
+BRACKET = """
+from build123d import *
+
+LENGTH = 60 # Length [30..200 mm]
+WIDTH = 40 # Width [20..120 mm]
+THICKNESS = 10 # Thickness [4..30 mm]
+
+with BuildPart() as plate:
+ Box(LENGTH, WIDTH, THICKNESS)
+ fillet(plate.edges().filter_by(Axis.Z), radius=5)
+ with Locations(plate.faces().sort_by(Axis.Z)[-1]):
+ with GridLocations(LENGTH - 20, WIDTH - 20, 2, 2):
+ CounterBoreHole(radius=2, counter_bore_radius=3.5, counter_bore_depth=2)
+
+result = plate.part
+print("built", LENGTH)
+"""
+
+
+def build(code):
+ return main.run_build(textwrap.dedent(code))
+
+
+class SandboxBuildTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ main.pool.refill()
+
+ @classmethod
+ def tearDownClass(cls):
+ main.pool.close()
+
+ def test_builds_a_real_part_with_every_artifact(self):
+ out = build(BRACKET)
+ self.assertTrue(out["ok"], out.get("error"))
+ size = out["metrics"]["size_mm"]
+ self.assertAlmostEqual(size[0], 60, places=2)
+ self.assertAlmostEqual(size[1], 40, places=2)
+ self.assertAlmostEqual(size[2], 10, places=2)
+ self.assertTrue(out["metrics"]["valid"])
+ self.assertEqual(out["metrics"]["solids"], 1)
+ self.assertLess(out["metrics"]["volume_mm3"], 60 * 40 * 10)
+ art = {k: base64.b64decode(v) for k, v in out["artifacts"].items()}
+ self.assertTrue(art["glb"].startswith(b"glTF"))
+ self.assertIn(b"ISO-10303-21", art["step"][:200])
+ self.assertGreater(len(art["stl"]), 84)
+ self.assertIn(b"<svg", art["thumb_svg"][:400])
+ self.assertIn(b"ISOMETRIC", art["drawing_svg"])
+ self.assertIn("built 60", out["log"])
+ if main.REQUIRE_SECCOMP:
+ self.assertTrue(out["seccomp"])
+
+ def test_runtime_error_reports_the_program_line(self):
+ out = build("from build123d import *\nx = 1\nresult = Box(10, 10, 10) / 0\n")
+ self.assertFalse(out["ok"])
+ self.assertEqual(out["error"]["kind"], "runtime")
+ self.assertEqual(out["error"]["line"], 3)
+
+ def test_missing_result_is_explained(self):
+ out = build("from build123d import *\nshape = Box(1, 1, 1)\n")
+ self.assertFalse(out["ok"])
+ self.assertEqual(out["error"]["kind"], "result")
+
+ def test_a_lone_builder_is_accepted_as_the_result(self):
+ out = build("from build123d import *\nwith BuildPart() as p:\n Box(5, 5, 5)\n")
+ self.assertTrue(out["ok"], out.get("error"))
+
+ def test_two_dimensional_result_is_refused(self):
+ out = build("from build123d import *\nwith BuildSketch() as s:\n Circle(5)\nresult = s\n")
+ self.assertFalse(out["ok"])
+ self.assertIn("2D", out["error"]["message"])
+
+ def test_policy_refusal_is_reported(self):
+ out = build("import os\nresult = os.listdir('/')\n")
+ self.assertFalse(out["ok"])
+ self.assertEqual(out["error"]["kind"], "policy")
+
+ def test_builtins_handle_is_refused(self):
+ out = build("from build123d import *\nimport math\nm = __builtins__\n")
+ self.assertEqual(out["error"]["kind"], "policy")
+
+ def test_infinite_loop_is_killed(self):
+ out = build("x = 0\nwhile True:\n x += 1\n")
+ self.assertFalse(out["ok"])
+ self.assertEqual(out["error"]["kind"], "timeout")
+
+ def test_memory_bomb_is_contained(self):
+ out = build("x = [0] * (10 ** 10)\n")
+ self.assertFalse(out["ok"])
+ self.assertEqual(out["error"]["kind"], "memory")
+
+ def test_oversized_fillet_is_reduced_and_reported(self):
+ out = build(
+ "from build123d import *\n"
+ "with BuildPart() as p:\n"
+ " Box(20, 20, 2)\n"
+ " fillet(p.edges().group_by(Axis.Z)[-1], radius=3)\n"
+ "result = p.part\n"
+ )
+ self.assertTrue(out["ok"], out.get("error"))
+ self.assertTrue(any("fillet 3 mm" in a for a in out["adjustments"]), out["adjustments"])
+
+ def test_impossible_fillet_is_skipped_and_reported(self):
+ out = build(
+ "from build123d import *\n"
+ "with BuildPart() as p:\n"
+ " Box(20, 20, 0.4)\n"
+ " fillet(p.edges(), radius=5)\n"
+ "result = p.part\n"
+ )
+ self.assertTrue(out["ok"], out.get("error"))
+ self.assertTrue(any("left the edges sharp" in a for a in out["adjustments"]), out["adjustments"])
+ self.assertAlmostEqual(out["metrics"]["volume_mm3"], 160, places=1)
+
+ def test_impossible_algebra_fillet_returns_the_part(self):
+ out = build(
+ "from build123d import *\n"
+ "box = Box(20, 20, 0.4)\n"
+ "result = fillet(box.edges(), radius=5)\n"
+ )
+ self.assertTrue(out["ok"], out.get("error"))
+ self.assertAlmostEqual(out["metrics"]["volume_mm3"], 160, places=1)
+
+ def test_standard_parts_from_bd_warehouse(self):
+ out = build(
+ "from build123d import *\n"
+ "from bd_warehouse.gear import SpurGear\n"
+ "result = SpurGear(module=2, tooth_count=20, pressure_angle=20, thickness=8, root_fillet=0.5)\n"
+ )
+ self.assertTrue(out["ok"], out.get("error"))
+ self.assertAlmostEqual(out["metrics"]["size_mm"][0], 44, places=0)
+
+ def test_module_object_import_is_refused_at_runtime(self):
+ out = build("from build123d import exporters\n")
+ self.assertFalse(out["ok"])
+ self.assertIn("module", out["error"]["message"])
+
+ def test_pool_recovers_after_failures(self):
+ out = build(BRACKET)
+ self.assertTrue(out["ok"], out.get("error"))
+
+
+class FailureClassificationTests(unittest.TestCase):
+ def test_kernel_segfault_names_the_program_line(self):
+ stderr = 'Fatal Python error: Segmentation fault\n\nCurrent thread:\n File "<design>", line 14 in <module>\n'
+ failure = main._signal_failure(-11, stderr)
+ self.assertEqual(failure["kind"], "crash")
+ self.assertEqual(failure["line"], 14)
+ self.assertIn("line 14", failure["message"])
+
+ def test_cpu_and_memory_limits(self):
+ self.assertEqual(main._signal_failure(-24, "")["kind"], "timeout")
+ self.assertEqual(main._signal_failure(-9, "")["kind"], "memory")
+ self.assertEqual(main._signal_failure(-6, "")["kind"], "memory")
+
+
+PROBE = r"""
+import errno, os, socket, sys
+sys.path.insert(0, "/app" if os.path.isdir("/app") else os.getcwd())
+from sandbox_child import install_seccomp
+results = {"uid": os.getuid(), "seccomp": install_seccomp()}
+try:
+ socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ results["socket"] = "opened"
+except OSError as exc:
+ results["socket"] = exc.errno
+try:
+ os.execv("/bin/true", ["/bin/true"])
+except OSError as exc:
+ results["exec"] = exc.errno
+try:
+ pid = os.fork()
+ if pid == 0:
+ os._exit(0)
+ results["fork"] = "forked"
+except OSError as exc:
+ results["fork"] = exc.errno
+try:
+ open("/proc/1/environ", "rb").read()
+ results["parent_env"] = "read"
+except OSError as exc:
+ results["parent_env"] = exc.errno
+import threading
+t = threading.Thread(target=lambda: None); t.start(); t.join()
+results["threads"] = "ok"
+print(repr(results))
+"""
+
+
+class IsolationLayerTests(unittest.TestCase):
+ """Each layer on its own, so a policy bypass would still hit a wall."""
+
+ def test_seccomp_and_uid_drop(self):
+ drop = os.geteuid() == 0
+ proc = subprocess.run(
+ [sys.executable, "-c", PROBE],
+ capture_output=True,
+ text=True,
+ env={"PATH": "/usr/bin:/bin", "OMP_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2"},
+ cwd=os.path.dirname(os.path.abspath(__file__)),
+ user=main.SANDBOX_UID if drop else None,
+ group=main.SANDBOX_UID if drop else None,
+ extra_groups=[] if drop else None,
+ preexec_fn=main._limits,
+ timeout=60,
+ )
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ results = eval(proc.stdout.strip()) # noqa: S307 (our own repr, test only)
+ if not main.REQUIRE_SECCOMP and not results["seccomp"]:
+ self.skipTest("seccomp unavailable on this host")
+ self.assertTrue(results["seccomp"])
+ self.assertEqual(results["socket"], 1) # EPERM
+ self.assertEqual(results["exec"], 1)
+ self.assertEqual(results["fork"], 1)
+ self.assertEqual(results["threads"], "ok")
+ if drop:
+ self.assertEqual(results["uid"], main.SANDBOX_UID)
+ self.assertNotEqual(results["parent_env"], "read")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/workers/cad-forge/worker_security.py b/workers/cad-forge/worker_security.py
new file mode 100644
index 000000000..a0360fe96
--- /dev/null
+++ b/workers/cad-forge/worker_security.py
@@ -0,0 +1,233 @@
+"""
+Shared security helpers for the three.ws GPU/CPU workers.
+
+This module is intentionally dependency-light (stdlib only) so it can be
+COPYed verbatim into every worker's Docker build context. The same canonical
+file lives in each worker directory; keep them byte-identical when editing.
+
+It provides three primitives that every worker needs:
+
+ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).
+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied
+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata
+ IP rejection, per-hop redirect re-validation, and a bounded response size.
+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged
+ message safe to persist/return to callers, after logging the full
+ traceback server-side only.
+"""
+
+from __future__ import annotations
+
+import hmac
+import ipaddress
+import logging
+import socket
+import uuid
+from typing import Iterable, Optional
+from urllib.parse import urlsplit
+
+import httpx
+
+log = logging.getLogger("worker_security")
+
+# ── auth ────────────────────────────────────────────────────────────────────────
+
+
+def require_api_key(authorization: Optional[str], api_key: str) -> None:
+ """Validate a ``Bearer <token>`` header in constant time.
+
+ Raises ``PermissionError`` on any failure so callers can translate it into
+ the framework's 401 (FastAPI workers map this to HTTPException(401)).
+ """
+ # Fail closed on an empty configured key: with api_key == "" a bare
+ # "Bearer " header would otherwise strip to "" and compare equal.
+ if not api_key:
+ raise PermissionError("worker api key not configured")
+ if not authorization or not authorization.startswith("Bearer "):
+ raise PermissionError("missing bearer token")
+ token = authorization[len("Bearer "):].strip()
+ if not token:
+ raise PermissionError("missing bearer token")
+ # Compare bytes: hmac.compare_digest is timing-safe, and on str operands it
+ # raises TypeError for non-ASCII input, which would surface as a 500.
+ if not hmac.compare_digest(token.encode("utf-8"), api_key.encode("utf-8")):
+ raise PermissionError("invalid api key")
+
+
+# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────
+
+# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes
+# are comfortably under this; anything larger is almost certainly abuse.
+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB
+_MAX_REDIRECTS = 4
+
+
+class UnsafeUrlError(ValueError):
+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""
+
+
+def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:
+ """Reject any address that could reach internal infrastructure.
+
+ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud
+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),
+ multicast, reserved, unspecified, and any other non-global address (CGNAT
+ 100.64.0.0/10 included). IPv4-mapped IPv6 addresses
+ are unwrapped first so a mapped private v4 can't slip through.
+ """
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ return (
+ ip.is_private
+ or ip.is_loopback
+ or ip.is_link_local
+ or ip.is_multicast
+ or ip.is_reserved
+ or ip.is_unspecified
+ # Anything not globally routable, which also covers the CGNAT shared
+ # space 100.64.0.0/10 that is_private does not flag.
+ or not ip.is_global
+ )
+
+
+def _resolve_safe_host(host: str) -> None:
+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.
+
+ Resolving and checking every returned address closes the gap where a name
+ resolves to both a public and a private address.
+ """
+ if not host:
+ raise UnsafeUrlError("missing host")
+ try:
+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
+ except socket.gaierror as exc:
+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc
+
+ addrs = {info[4][0] for info in infos}
+ if not addrs:
+ raise UnsafeUrlError(f"no addresses for host: {host}")
+ for addr in addrs:
+ ip = ipaddress.ip_address(addr)
+ if _is_blocked_ip(ip):
+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")
+
+
+def assert_safe_url(url: str, *, allow_http: bool = False) -> str:
+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.
+
+ https is required by default; ``allow_http`` exists only for callers that
+ legitimately need cleartext (not used by the workers).
+ """
+ parts = urlsplit(url)
+ scheme = parts.scheme.lower()
+ allowed = ("https", "http") if allow_http else ("https",)
+ if scheme not in allowed:
+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")
+ if not parts.hostname:
+ raise UnsafeUrlError("missing host")
+ _resolve_safe_host(parts.hostname)
+ return url
+
+
+def fetch_remote_bytes(
+ url: str,
+ *,
+ timeout: float = 30.0,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Fetch ``url`` safely and return its body bytes.
+
+ Hardening applied:
+ * https-only (unless ``allow_http``).
+ * every URL — including each redirect target — is DNS-resolved and
+ rejected if it maps to a private/loopback/link-local/metadata address.
+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is
+ re-validated; httpx's own redirect following is disabled.
+ * the response body is streamed and aborted once it exceeds ``max_bytes``.
+
+ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /
+ ``ValueError`` for transport or size failures.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:
+ for _ in range(_MAX_REDIRECTS + 1):
+ with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in resp.iter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+async def fetch_remote_bytes_async(
+ client: "httpx.AsyncClient",
+ url: str,
+ *,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.
+
+ The provided ``client`` MUST be constructed with ``follow_redirects=False``
+ so this function can re-validate each redirect hop itself.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ for _ in range(_MAX_REDIRECTS + 1):
+ async with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ async for chunk in resp.aiter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+# ── opaque error handling ───────────────────────────────────────────────────────
+
+
+def safe_error(exc: BaseException, *, context: str = "") -> str:
+ """Log the full traceback server-side and return an opaque client message.
+
+ Never leak ``traceback.format_exc()`` (absolute paths, library versions,
+ internal hostnames, fragments of upstream responses) to callers. A short
+ correlation id is embedded in both the log line and the returned string so
+ operators can join a client-reported failure to the server log.
+ """
+ correlation_id = uuid.uuid4().hex[:12]
+ label = f"{context} " if context else ""
+ log.exception("%serror [correlation_id=%s]", label, correlation_id)
+ return f"internal error (ref {correlation_id})"