Repository Public
1import { spawn, execFile } from "node:child_process";2import { createHash } from "node:crypto";3import { constants as FS, existsSync } from "node:fs";4import { chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, writeFile } from "node:fs/promises";5import os from "node:os";6import path from "node:path";78/**9 * BAC À SABLE PYTHON — exécute du Python ÉCRIT PAR UN MODÈLE (donc NON FIABLE) pour la visualisation procédurale : soit des données10 * numériques validées rendues en JSON (`data`), soit des trames matplotlib (`frames`). L'hôte de production porte des clés d'API dans11 * son environnement et son `.env` : ce code ne doit jamais tourner sans confinement.12 *13 * - Frontière de sécurité : `sandbox-exec` (Seatbelt, noyau macOS) avec un profil `(deny default)` généré par exécution — aucun réseau,14 * aucun fork ni exec (hormis le binaire python lui-même), lecture limitée à l'installation Python, au venv figé, au harnais et au15 * dossier d'entrée, écriture dans UN dossier temporaire neuf. Sans `sandbox-exec`, on REFUSE (`no_sandbox`), sauf16 * `CLIP_PYSANDBOX_UNSAFE=1` (développement seulement).17 * - Défense en profondeur (contournable, voir py/sandbox/runner.py) : contrôle statique du source ici, puis dans le harnais filtre18 * d'import, builtins réduits, crochet d'audit, limites de ressources (rlimits).19 * - Environnement de l'enfant : sept variables fixes (PATH, HOME, TMPDIR, LANG, MPLCONFIGDIR, PYTHONHASHSEED, PYTHONDONTWRITEBYTECODE), RIEN de l'environnement du parent.20 * - Rien de ce que rend le processus confiné n'est cru sur parole : la ligne JSON finale, `data.json` et chaque PNG sont revérifiés ici21 * (fichiers ordinaires, jamais de lien symbolique ni de lien dur, tailles plafonnées, dimensions PNG exactes).22 * - Garde-fous extérieurs au processus : délai mur (SIGKILL du groupe), surveillance de la mémoire résidente et de l'espace disque.23 *24 * Le venv (`py/sandbox/.venv`, versions figées par `py/sandbox/uv.lock`) est préparé HORS du bac à sable par `ensurePyEnv()`25 * (`uv sync --frozen`, réseau requis une fois) ; l'exécution confinée lance directement le python du venv.26 */2728export type PyMode = "data" | "frames";29export type PySandboxErrorCode = "bad_input" | "no_sandbox" | "env_missing" | "timeout" | "memory" | "runtime" | "bad_output";3031export class PySandboxError extends Error {32 constructor(message: string, public code: PySandboxErrorCode, public details?: { stderr?: string; stdout?: string; traceback?: string }) { super(message); this.name = "PySandboxError"; }33}3435export interface PyRunOptions {36 code: string; mode: PyMode; params?: Record<string, unknown>;37 width?: number; height?: number; fps?: number; seconds?: number;38 /** Délai mur de toute l'exécution (défaut 120 s). Le temps processeur est plafonné au même ordre de grandeur par RLIMIT_CPU. */39 timeoutMs?: number;40 /** Mémoire que le code peut allouer AU-DELÀ du préchargement de numpy/matplotlib (défaut 2048 Mo). */41 memoryMb?: number;42}4344export interface PyResult {45 /** Vrai si le code a tourné sans erreur ET qu'aucun invariant de `validate()` n'a échoué. */46 ok: boolean;47 /** Mode `data` : ce que `compute()` a rendu (présent aussi quand des invariants échouent, pour le diagnostic). */48 data?: unknown;49 /** Mode `data` : invariants NON respectés rendus par `validate()` (vide = tout tient). */50 checks?: string[];51 /** Mode `frames` : dossier des trames `f%06d.png` (RGBA, exactement width×height). À libérer par `cleanup()`. */52 framesDir?: string; frames?: number;53 /** Durée mur de l'exécution, mesurée ici. */54 seconds: number;55 /** Erreur du code de scène, lisible par le modèle, et lignes fautives de SON code. */56 error?: string; traceback?: string;57 /** Ce que le code a écrit sur stdout/stderr (tronqué). */58 stdout?: string;59 /** `kernel` : le bac à sable du noyau était actif ; `profile` : le profil Seatbelt appliqué, mot pour mot (« none » en mode non confiné). */60 sandbox: { kernel: boolean; profile: string };61 /** Supprime le dossier temporaire de l'exécution (trames comprises). Idempotent. */62 cleanup(): Promise<void>;63}6465// ── réglages ─────────────────────────────────────────────────────────────────66export const MAX_CODE_BYTES = 200_000;67const MAX_PARAMS_BYTES = 1_000_000;68const MAX_DATA_BYTES = 5 * 1024 * 1024; // même plafond que runner.py69const MAX_STDOUT_BYTES = 2 * 1024 * 1024;70const MAX_FRAMES = 36_000;71const DEFAULT_TIMEOUT_MS = 120_000;72const DEFAULT_MEMORY_MB = 2048;73/** Marge de la surveillance de mémoire résidente au-dessus de `memoryMb` : interpréteur + numpy + matplotlib préchargés. */74const RSS_SLACK_MB = 512;75const DISK_MB = Math.max(64, Number(process.env.CLIP_PYSANDBOX_DISK_MB) || 4096);76const SANDBOX_EXEC = "/usr/bin/sandbox-exec";77/** Jointure de chemins opaque pour l'empaqueteur (sinon Turbopack suit `py/sandbox` et bute sur les liens symboliques du venv). */78const pj = (...parts: string[]) => path.join(...parts);79const PY_DIR = process.env.CLIP_PYSANDBOX_DIR ?? pj(/* turbopackIgnore: true */ process.cwd(), "py", "sandbox");80const CONCURRENCY = Math.max(1, Number(process.env.CLIP_PYSANDBOX_CONCURRENCY) || Math.max(1, Math.floor(os.availableParallelism() / 2)));8182/** Modules importables par le code de scène (premier segment). Tenir en phase avec ALLOWED de py/sandbox/runner.py (un test le vérifie). */83export const ALLOWED_MODULES = ["numpy", "scipy", "matplotlib", "mpl_toolkits", "sympy", "mpmath", "math", "cmath", "random", "statistics", "itertools", "functools",84 "collections", "dataclasses", "typing", "json", "fractions", "decimal", "bisect", "heapq", "operator", "enum", "re", "string", "colorsys", "numbers", "copy", "abc",85 "array", "__future__"] as const;8687const unsafeAllowed = () => process.env.CLIP_PYSANDBOX_UNSAFE === "1";88/** Réservé aux tests : coupe le contrôle statique et les gardes Python pour prouver que le NOYAU seul retient le code. Jamais en production. */89const guardsOff = () => process.env.CLIP_PYSANDBOX_TEST_NO_PYGUARD === "1" && process.env.NODE_ENV !== "production";9091// ── contrôle statique du source (défense en profondeur) ──────────────────────92/** Remplace commentaires et contenus de chaînes par des blancs (mêmes positions de ligne) pour ne contrôler que le code. */93function stripStringsAndComments(src: string): string {94 let out = "", i = 0;95 const n = src.length;96 while (i < n) {97 const c = src[i];98 if (c === "#") { while (i < n && src[i] !== "\n") i++; continue; }99 if (c === '"' || c === "'") {100 const triple = src.startsWith(c.repeat(3), i), q = triple ? c.repeat(3) : c;101 out += q; i += q.length;102 while (i < n && !src.startsWith(q, i)) {103 if (src[i] === "\\") { i += 2; continue; }104 if (src[i] === "\n") { if (!triple) break; out += "\n"; }105 i++;106 }107 if (src.startsWith(q, i)) { out += q; i += q.length; }108 continue;109 }110 out += c; i++;111 }112 return out;113}114115const FORBIDDEN_CALLS: [RegExp, string][] = [116 [/(?<![\w.])open\s*\(/, "open() : aucun accès aux fichiers. Rendre les données par compute() ou dessiner dans draw()"],117 [/(?<![\w.])(eval|exec|compile)\s*\(/, "eval(), exec() et compile() : pas d'évaluation dynamique de code"],118 [/(?<![\w.])(input|breakpoint)\s*\(/, "input() et breakpoint() : le code tourne sans terminal"],119 [/__import__|\bimportlib\b/, "__import__ et importlib : utiliser une instruction `import` d'un module permis"],120 [/__(subclasses|globals|builtins|bases|mro|code|closure|getattribute|loader|spec|dict|class|reduce|reduce_ex)__/, "introspection d'objets internes (__subclasses__, __globals__, __class__, __dict__…) : inutile pour une visualisation"],121 [/(?<![\w.])(globals|locals|vars)\s*\(/, "globals(), locals() et vars() : inutiles pour une visualisation"],122 [/\bplt\.show\s*\(|\.savefig\s*\(|\bnp\.(save|savez|savez_compressed|savetxt|load|loadtxt|genfromtxt|fromfile|memmap)\s*\(|\.tofile\s*\(/, "lecture ou écriture de fichiers (savefig, np.save, np.load, plt.show…) : le moteur écrit lui-même les trames et data.json"],123];124125/**126 * Contrôle statique du source : rend la liste des problèmes, en français, formulés pour qu'un modèle puisse corriger. Vide = accepté.127 * Défense en profondeur seulement (une expression régulière ne retient pas un adversaire) : la frontière est le bac à sable du noyau.128 */129export function checkPythonSource(code: string, mode: PyMode): string[] {130 const problems: string[] = [];131 if (typeof code !== "string" || !code.trim()) return ["Code vide"];132 const bytes = Buffer.byteLength(code, "utf8");133 if (bytes > MAX_CODE_BYTES) return [`Code trop volumineux : ${bytes} octets (maximum ${MAX_CODE_BYTES})`];134 if (code.includes("\0")) return ["Le code contient un octet nul"];135 const bare = stripStringsAndComments(code), lines = bare.split("\n");136 const allowed = new Set<string>(ALLOWED_MODULES);137 const seen = new Set<string>();138 lines.forEach((line, i) => {139 for (const stmt of line.split(";")) {140 const m = /^\s*(?:from\s+([\w.]+)\s+import\b|import\s+(.+))/.exec(stmt);141 if (!m) continue;142 const names = m[1] ? [m[1]] : m[2].split(",").map((s) => s.trim().split(/\s+as\s+/)[0].trim());143 for (const name of names) {144 const top = name.split(".")[0];145 if (!top || allowed.has(top) || seen.has(top)) continue;146 seen.add(top);147 problems.push(`ligne ${i + 1} : module « ${top} » interdit dans le bac à sable (ni fichiers, ni réseau, ni processus). Modules permis : ${ALLOWED_MODULES.filter((a) => !a.startsWith("_") && a !== "mpmath" && a !== "mpl_toolkits").join(", ")}`);148 }149 }150 });151 for (const [re, why] of FORBIDDEN_CALLS) {152 const i = lines.findIndex((l) => re.test(l));153 if (i >= 0) problems.push(`ligne ${i + 1} : interdit — ${why}`);154 }155 const need = mode === "data" ? "compute" : "draw";156 if (!new RegExp(`^def\\s+${need}\\s*\\(`, "m").test(bare)) problems.push(mode === "data" ? "Le code doit définir `def compute(params: dict) -> dict` au premier niveau" : "Le code doit définir `def draw(fig, t: float, params: dict) -> None` au premier niveau");157 return problems;158}159160// ── profil Seatbelt ──────────────────────────────────────────────────────────161const q = (p: string) => `"${p.replace(/[\\"]/g, "\\$&")}"`;162163/** Liens symboliques rencontrés en résolvant `p` composant par composant (le noyau doit pouvoir lire chacun d'eux pour les suivre). */164async function symlinksOnPath(p: string): Promise<string[]> {165 const links: string[] = [];166 let rest = path.resolve(p).split(path.sep).filter(Boolean), cur = "/";167 for (let hops = 0; rest.length && hops < 64;) {168 const next = pj(cur, rest[0]);169 const st = await lstat(next);170 if (st.isSymbolicLink()) {171 links.push(next); hops++;172 const target = path.resolve(cur, await readlink(next));173 rest = [...target.split(path.sep).filter(Boolean), ...rest.slice(1)]; cur = "/";174 } else { cur = next; rest = rest.slice(1); }175 }176 return links;177}178179export interface SeatbeltPaths {180 /** Binaire python réel (liens résolus) : seul exécutable permis. */ pythonBin: string;181 /** Racine de l'installation Python (bibliothèque standard, libpython). */ pythonHome: string;182 /** Venv figé (site-packages), en lecture seule. */ venv: string;183 /** Harnais de confiance. */ runner: string;184 /** Liens symboliques à traverser entre `venv/bin/python` et `pythonBin`. */ links: string[];185 /** Dossier d'entrée de l'exécution (code, paramètres), en lecture seule. */ input: string;186 /** SEUL dossier inscriptible : sortie, HOME, MPLCONFIGDIR, TMPDIR. */ writable: string;187}188189/**190 * Profil Seatbelt d'une exécution. Tout est refusé par défaut ; chaque permission ci-dessous a été vérifiée nécessaire (macOS 27.0, arm64),191 * sauf les dossiers système publics (/usr/lib, /System/Library/…), gardés pour les versions de macOS qui ne servent pas toutes leurs192 * bibliothèques depuis le cache partagé de dyld. Aucun service Mach (trousseau, presse-papiers, AppleEvents…), aucun IOKit, aucune IPC,193 * et aucune métadonnée (stat) hors des chemins lisibles : Python s'en passe, et le code ne peut pas sonder l'existence de fichiers.194 */195export function seatbeltProfile(p: SeatbeltPaths): string {196 return [197 "(version 1)",198 "(deny default)",199 "; aucun réseau (TCP, UDP, sockets Unix, résolution de noms), aucun nouveau processus",200 "(deny network*)",201 "(deny process-fork)",202 `(allow process-exec (literal ${q(p.pythonBin)}))`,203 "; lecture : bibliothèques et polices du système, installation Python, venv figé, harnais, entrée de l'exécution",204 "(allow file-read*",205 ...["/usr/lib", "/System/Library/Frameworks", "/System/Library/PrivateFrameworks", "/System/Library/Fonts", "/System/Volumes/Preboot/Cryptexes/OS", "/System/Cryptexes/OS"].map((s) => ` (subpath ${q(s)})`),206 ` (subpath ${q(p.pythonHome)})`,207 ` (subpath ${q(p.venv)})`,208 ` (literal ${q(p.runner)})`,209 ...p.links.map((l) => ` (literal ${q(l)})`),210 ` (subpath ${q(p.input)})`,211 ` (subpath ${q(p.writable)}))`,212 "; dyld lit l'entrée de la racine au lancement ; /dev/null et l'aléa du noyau",213 '(allow file-read-data (literal "/"))',214 '(allow file-read* file-write-data (literal "/dev/null"))',215 '(allow file-read* (literal "/dev/urandom") (literal "/dev/random"))',216 "; écriture : uniquement le dossier jetable de cette exécution",217 `(allow file-write* (subpath ${q(p.writable)}))`,218 "; os.uname() (numpy) et détection du processeur",219 '(allow sysctl-read (sysctl-name-prefix "hw.") (sysctl-name "kern.ostype") (sysctl-name "kern.osrelease") (sysctl-name "kern.version") (sysctl-name "kern.hostname"))',220 "",221 ].join("\n");222}223224// ── environnement Python (hors bac à sable, une fois) ────────────────────────225export interface PyEnv { python: string; versions: Record<string, string> }226interface PyEnvFull extends PyEnv { dir: string; venv: string; runner: string; pythonBin: string; pythonHome: string; links: string[]; fontCache: string | null }227interface Marker { key: string; versions: Record<string, string>; fontCache: string | null; allowed: string[] }228229let envPromise: Promise<PyEnvFull> | null = null;230const sha = (b: Buffer | string) => createHash("sha256").update(b).digest("hex");231const hasSandboxExec = () => process.platform === "darwin" && existsSync(SANDBOX_EXEC);232233function findUv(): string | null {234 const dirs = [...(process.env.PATH ?? "").split(":"), pj(os.homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin"].filter(Boolean);235 for (const d of dirs) { const f = pj(d, "uv"); if (existsSync(f)) return f; }236 return null;237}238239function run(cmd: string, args: string[], o: { env: Record<string, string>; cwd?: string; timeoutMs: number }): Promise<{ code: number | null; stdout: string; stderr: string }> {240 return new Promise((resolve, reject) => {241 execFile(cmd, args, { env: o.env as unknown as NodeJS.ProcessEnv, cwd: o.cwd, timeout: o.timeoutMs, killSignal: "SIGKILL", maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {242 if (err && typeof (err as NodeJS.ErrnoException).code === "string") return reject(err);243 resolve({ code: err ? ((err as { code?: number }).code ?? 1) : 0, stdout: String(stdout), stderr: String(stderr) });244 });245 });246}247248async function prepareEnv(): Promise<PyEnvFull> {249 let dir: string;250 try { dir = await realpath(PY_DIR); } catch { throw new PySandboxError(`Projet du bac à sable Python introuvable : ${PY_DIR}`, "env_missing"); }251 const runner = pj(dir, "runner.py"), lock = pj(dir, "uv.lock"), venv = pj(dir, ".venv"), python = pj(venv, "bin/python");252 if (!existsSync(runner) || !existsSync(lock)) throw new PySandboxError(`Bac à sable Python incomplet : runner.py ou uv.lock manquant dans ${dir}`, "env_missing");253 const lockHash = sha(await readFile(lock));254 const stateDir = pj(venv, ".spclip-pysandbox"), markerFile = pj(stateDir, "env.json");255 const readMarker = async (): Promise<Marker | null> => { try { return JSON.parse(await readFile(markerFile, "utf8")) as Marker; } catch { return null; } };256 let marker = await readMarker();257 void sweepStale().catch(() => undefined);258259 // 1. venv conforme au fichier de verrouillage (réseau requis ici, jamais dans le bac à sable)260 if (!existsSync(python) || !marker || !marker.key.startsWith(lockHash)) {261 const uv = findUv();262 if (!uv) throw new PySandboxError(`Environnement Python absent et « uv » introuvable. Installer uv puis lancer : uv sync --project ${dir} --frozen`, "env_missing");263 let r: { code: number | null; stderr: string };264 try { r = await run(uv, ["sync", "--project", dir, "--frozen", "--no-progress"], { env: { PATH: `${path.dirname(uv)}:/usr/bin:/bin`, HOME: os.homedir(), LANG: "en_US.UTF-8" }, timeoutMs: 600_000 }); }265 catch (e) { throw new PySandboxError(`uv sync impossible : ${(e as Error).message.split("\n")[0]}`, "env_missing"); }266 if (r.code !== 0 || !existsSync(python)) throw new PySandboxError(`uv sync a échoué (${r.code}) : ${r.stderr.trim().split("\n").slice(-3).join(" | ")}`, "env_missing");267 marker = null;268 }269 const pythonBin = await realpath(python), pythonHome = path.dirname(path.dirname(pythonBin));270 const links = (await symlinksOnPath(python)).filter((l) => !l.startsWith(venv + path.sep));271 const base = { dir, venv, runner, python, pythonBin, pythonHome, links };272273 // 2. amorçage : versions des paquets + cache de polices matplotlib (≈ 2 s confiné ; 25 s à chaque exécution sinon), construit DANS le274 // bac à sable par le seul harnais de confiance, puis rangé dans le venv (lecture seule pour le code de scène).275 const key = `${lockHash}:${sha(await readFile(runner)).slice(0, 16)}:${pythonBin}:${os.release()}`;276 if (!marker || marker.key !== key || (marker.fontCache && !existsSync(pj(stateDir, marker.fontCache)))) {277 const w = await makeWorkDir();278 try {279 const out = await spawnConfined({ ...base, fontCache: null, versions: {} }, w, ["--mode", "warm"], { timeoutMs: 180_000, memoryMb: 4096, kernel: hasSandboxExec() });280 const line = lastJson(out.stdout);281 if (!line || line.ok !== true || typeof line.versions !== "object") throw new PySandboxError(`Amorçage de l'environnement Python impossible : ${(out.stderr || out.stdout).trim().split("\n").slice(-3).join(" | ") || `code ${out.code}, signal ${out.signal}`}`, "env_missing", { stderr: out.stderr });282 const font = (await readdir(pj(w.writable, "mpl"))).find((f) => /^fontlist-.*\.json$/.test(f)) ?? null;283 await mkdir(stateDir, { recursive: true });284 if (font) { const tmp = pj(stateDir, `.${process.pid}.${font}`); await copyFile(pj(w.writable, "mpl", font), tmp); await rename(tmp, pj(stateDir, font)); }285 marker = { key, versions: line.versions as Record<string, string>, fontCache: font, allowed: (line.allowed as string[]) ?? [] };286 const tmp = `${markerFile}.${process.pid}`;287 await writeFile(tmp, JSON.stringify(marker));288 await rename(tmp, markerFile);289 } finally { await removeTree(w.root); }290 }291 return { ...base, versions: marker.versions, fontCache: marker.fontCache ? pj(stateDir, marker.fontCache) : null };292}293294/**295 * Prépare (une fois par processus, résultat en cache) le venv figé du bac à sable : `uv sync --frozen` s'il manque ou si `uv.lock` a296 * changé, puis amorçage confiné (versions, cache de polices). Lève `PySandboxError` `env_missing` ou `no_sandbox`.297 */298export async function ensurePyEnv(): Promise<PyEnv> {299 const e = await fullEnv();300 return { python: e.python, versions: { ...e.versions } };301}302function fullEnv(): Promise<PyEnvFull> {303 if (!hasSandboxExec() && !unsafeAllowed()) return Promise.reject(noSandbox());304 envPromise ??= prepareEnv().catch((e) => { envPromise = null; throw e; });305 return envPromise;306}307const noSandbox = () => new PySandboxError(`Bac à sable du noyau indisponible (${SANDBOX_EXEC} absent, plateforme ${process.platform}) : le code Python généré n'est PAS exécuté. Pour le développement seulement : CLIP_PYSANDBOX_UNSAFE=1.`, "no_sandbox");308309export interface PySandboxCapabilities {310 /** Le moteur peut exécuter du Python généré sur cette machine. */ available: boolean;311 /** Confinement par le noyau (sandbox-exec). Faux = indisponible, ou mode non confiné de développement. */ kernel: boolean;312 /** Mode non confiné explicitement demandé (CLIP_PYSANDBOX_UNSAFE=1). */ unsafe: boolean;313 /** Raison de l'indisponibilité. */ reason?: string;314 modes: PyMode[]; allowedModules: string[]; versions?: Record<string, string>;315 limits: { timeoutMs: number; memoryMb: number; diskMb: number; codeBytes: number; dataBytes: number; concurrency: number };316}317/** Découverte de capacité pour les workers : ne lève jamais ; prépare l'environnement au besoin (première fois : `uv sync`). */318export async function pySandboxCapabilities(): Promise<PySandboxCapabilities> {319 const kernel = hasSandboxExec();320 const base = { kernel, unsafe: !kernel && unsafeAllowed(), modes: ["data", "frames"] as PyMode[], allowedModules: [...ALLOWED_MODULES],321 limits: { timeoutMs: DEFAULT_TIMEOUT_MS, memoryMb: DEFAULT_MEMORY_MB, diskMb: DISK_MB, codeBytes: MAX_CODE_BYTES, dataBytes: MAX_DATA_BYTES, concurrency: CONCURRENCY } };322 try { const env = await ensurePyEnv(); return { ...base, available: true, versions: env.versions }; }323 catch (e) { return { ...base, available: false, reason: (e as Error).message }; }324}325326// ── exécution confinée ───────────────────────────────────────────────────────327interface WorkDir { root: string; input: string; writable: string; out: string }328async function makeWorkDir(): Promise<WorkDir> {329 const root = await realpath(await mkdtemp(pj(os.tmpdir(), "spclip-py-")));330 const w: WorkDir = { root, input: pj(root, "in"), writable: pj(root, "w"), out: pj(root, "w", "out") };331 await mkdir(w.input);332 for (const d of ["", "out", "home", "mpl", "tmp"]) await mkdir(pj(w.writable, d));333 return w;334}335336/** Supprime un dossier d'exécution sans jamais suivre un lien posé par le code de scène (ni pour supprimer, ni pour changer des droits). */337async function removeTree(root: string): Promise<void> {338 try { await rm(root, { recursive: true, force: true, maxRetries: 2 }); return; } catch { /* dossiers rendus illisibles par la scène : on rétablit les droits */ }339 const fix = async (dir: string): Promise<void> => {340 const st = await lstat(dir).catch(() => null);341 if (!st || !st.isDirectory()) return;342 await chmod(dir, 0o700).catch(() => undefined);343 for (const name of await readdir(dir).catch(() => [] as string[])) await fix(pj(dir, name));344 };345 await fix(root);346 await rm(root, { recursive: true, force: true }).catch(() => undefined);347}348349async function treeBytes(dir: string, budget = { n: 200_000 }): Promise<number> {350 let total = 0;351 for (const name of await readdir(dir).catch(() => [] as string[])) {352 if (budget.n-- <= 0) return Number.MAX_SAFE_INTEGER; // trop de fichiers : traité comme un dépassement353 const st = await lstat(pj(dir, name)).catch(() => null);354 if (!st) continue;355 total += st.isDirectory() ? await treeBytes(pj(dir, name), budget) : st.size;356 }357 return total;358}359360function rssMb(pid: number): Promise<number> {361 return new Promise((resolve) => execFile("/bin/ps", ["-o", "rss=", "-p", String(pid)], { timeout: 2000 }, (_e, out) => resolve((Number(String(out).trim()) || 0) / 1024)));362}363364function lastJson(stdout: string): Record<string, unknown> | null {365 const lines = stdout.split("\n").map((l) => l.trim()).filter(Boolean);366 const last = lines[lines.length - 1];367 if (!last || !last.startsWith("{")) return null;368 try { const v: unknown = JSON.parse(last); return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null; } catch { return null; }369}370371interface Spawned { code: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string; killed: "timeout" | "memory" | "disk" | "output" | null; peakRssMb: number; profile: string }372373/** Enfants en cours : tués si ce processus se termine (sortie normale ou exception fatale ; un SIGKILL du worker, lui, ne prévient pas). */374const live = new Set<number>();375process.on("exit", () => { for (const pid of live) { try { process.kill(-pid, "SIGKILL"); } catch { /* déjà mort */ } } });376377/** Retire les dossiers d'exécution orphelins (worker tué en plein rendu) vieux de plus de deux heures. */378async function sweepStale(): Promise<void> {379 const base = await realpath(os.tmpdir()).catch(() => os.tmpdir());380 for (const name of await readdir(base).catch(() => [] as string[])) {381 if (!/^spclip-py-[A-Za-z0-9]{6}$/.test(name)) continue;382 const st = await lstat(pj(base, name)).catch(() => null);383 if (st?.isDirectory() && st.uid === process.getuid?.() && Date.now() - st.mtimeMs > 2 * 3600_000) await removeTree(pj(base, name));384 }385}386387let running = 0;388const queue: (() => void)[] = [];389async function acquire(): Promise<void> { if (running < CONCURRENCY) { running++; return; } await new Promise<void>((r) => queue.push(r)); }390function release(): void { const next = queue.shift(); if (next) next(); else running--; }391392/** Lance le harnais dans le bac à sable du noyau (ou sans, si `kernel` est faux : développement explicite seulement). */393async function spawnConfined(env: PyEnvFull, w: WorkDir, runnerArgs: string[], o: { timeoutMs: number; memoryMb: number; kernel: boolean }): Promise<Spawned> {394 const profile = o.kernel ? seatbeltProfile({ pythonBin: env.pythonBin, pythonHome: env.pythonHome, venv: env.venv, runner: env.runner, links: env.links, input: w.input, writable: w.writable }) : "none";395 const profileFile = pj(w.root, "profile.sb");396 if (o.kernel) await writeFile(profileFile, profile, { mode: 0o400 });397 if (env.fontCache) await copyFile(env.fontCache, pj(w.writable, "mpl", path.basename(env.fontCache))).catch(() => undefined);398 // -B : pas de .pyc ; -s : pas de site utilisateur ; -P : ni le dossier courant ni celui du script dans sys.path.399 const py = [env.python, "-B", "-s", "-P", env.runner, ...runnerArgs, "--write-root", w.writable, "--memory-mb", String(o.memoryMb), "--cpu-seconds", String(Math.ceil(o.timeoutMs / 1000) + 2)];400 const [cmd, args] = o.kernel ? [SANDBOX_EXEC, ["-f", profileFile, ...py]] : [py[0], py.slice(1)];401 // Environnement de l'enfant : construit de zéro. RIEN du parent (clés d'API, DATABASE_URL, APP_SECRET…) n'y entre.402 const childEnv: Record<string, string> = { PATH: "/usr/bin:/bin", HOME: pj(w.writable, "home"), TMPDIR: pj(w.writable, "tmp"), LANG: "en_US.UTF-8", MPLCONFIGDIR: pj(w.writable, "mpl"),403 PYTHONHASHSEED: "0", PYTHONDONTWRITEBYTECODE: "1" };404 await acquire();405 try {406 return await new Promise<Spawned>((resolve, reject) => {407 const child = spawn(cmd, args, { cwd: w.writable, env: childEnv as unknown as NodeJS.ProcessEnv, stdio: ["ignore", "pipe", "pipe"], detached: true });408 let stdout = "", stderr = "", outBytes = 0, peak = 0, killed: Spawned["killed"] = null, busy = false, ticks = 0;409 const kill = (why: NonNullable<Spawned["killed"]>) => {410 killed ??= why;411 try { if (child.pid) process.kill(-child.pid, "SIGKILL"); } catch { /* groupe déjà mort */ }412 try { child.kill("SIGKILL"); } catch { /* déjà mort */ }413 };414 if (child.pid) live.add(child.pid);415 const timer = setTimeout(() => kill("timeout"), o.timeoutMs);416 const watch = setInterval(() => {417 if (busy || !child.pid || child.exitCode !== null) return;418 busy = true;419 void (async () => {420 const rss = await rssMb(child.pid!);421 peak = Math.max(peak, rss);422 if (rss > o.memoryMb + RSS_SLACK_MB) kill("memory");423 else if (++ticks % 4 === 0 && (await treeBytes(w.writable)) > DISK_MB * 1024 * 1024) kill("disk");424 })().finally(() => { busy = false; });425 }, 250);426 child.stdout.on("data", (c: Buffer) => { outBytes += c.length; if (outBytes > MAX_STDOUT_BYTES) kill("output"); else stdout += c.toString("utf8"); });427 child.stderr.on("data", (c: Buffer) => { stderr = (stderr + c.toString("utf8")).slice(-16_000); });428 child.on("error", (e) => { clearTimeout(timer); clearInterval(watch); reject(new PySandboxError(`Lancement du bac à sable impossible : ${e.message}`, "runtime")); });429 child.on("close", (code, signal) => { clearTimeout(timer); clearInterval(watch); if (child.pid) live.delete(child.pid); resolve({ code, signal, stdout, stderr, killed, peakRssMb: Math.round(peak), profile }); });430 });431 } finally { release(); }432}433434function validateInput(o: PyRunOptions): Required<Pick<PyRunOptions, "width" | "height" | "fps" | "seconds" | "timeoutMs" | "memoryMb">> & { paramsJson: string } {435 const bad = (m: string) => new PySandboxError(m, "bad_input");436 if (o.mode !== "data" && o.mode !== "frames") throw bad(`Mode inconnu : ${String(o.mode)}`);437 const width = o.width ?? 1920, height = o.height ?? 1080, fps = o.fps ?? 30, seconds = o.seconds ?? 1, timeoutMs = o.timeoutMs ?? DEFAULT_TIMEOUT_MS, memoryMb = o.memoryMb ?? DEFAULT_MEMORY_MB;438 const ok = (n: number, lo: number, hi: number) => Number.isFinite(n) && n >= lo && n <= hi;439 if (!ok(width, 16, 4096) || !ok(height, 16, 4096) || !Number.isInteger(width) || !Number.isInteger(height)) throw bad(`Dimensions invalides : ${width}×${height}`);440 if (!ok(seconds, 0.03, 600)) throw bad(`Durée invalide : ${seconds} s`);441 if (!ok(fps, 1, 120)) throw bad(`Cadence invalide : ${fps}`);442 if (o.mode === "frames" && Math.round(seconds * fps) > MAX_FRAMES) throw bad(`Trop de trames : ${Math.round(seconds * fps)} (maximum ${MAX_FRAMES})`);443 if (!ok(timeoutMs, 500, 3_600_000)) throw bad(`Délai invalide : ${timeoutMs} ms`);444 if (!ok(memoryMb, 64, 65_536) || !Number.isInteger(memoryMb)) throw bad(`Plafond de mémoire invalide : ${memoryMb} Mo`);445 let paramsJson: string;446 try { paramsJson = JSON.stringify(o.params ?? {}); } catch (e) { throw bad(`Paramètres non sérialisables : ${(e as Error).message}`); }447 if (typeof o.params !== "undefined" && (o.params === null || typeof o.params !== "object" || Array.isArray(o.params))) throw bad("Les paramètres doivent être un objet");448 if (Buffer.byteLength(paramsJson) > MAX_PARAMS_BYTES) throw bad(`Paramètres trop volumineux (maximum ${MAX_PARAMS_BYTES} octets)`);449 if (!guardsOff()) { const problems = checkPythonSource(o.code, o.mode); if (problems.length) throw bad(`Code Python refusé avant exécution :\n- ${problems.join("\n- ")}`); }450 else if (typeof o.code !== "string" || Buffer.byteLength(o.code) > MAX_CODE_BYTES) throw bad("Code invalide");451 return { width, height, fps, seconds, timeoutMs, memoryMb, paramsJson };452}453454/** Lit un fichier produit par le code confiné : fichier ordinaire, un seul lien, jamais à travers un lien symbolique, taille plafonnée. */455async function readProduced(file: string, maxBytes: number, head?: number): Promise<Buffer> {456 const st = await lstat(file).catch(() => null);457 if (!st || !st.isFile() || st.nlink !== 1) throw new PySandboxError(`Sortie invalide : ${path.basename(file)} est absent ou n'est pas un fichier ordinaire`, "bad_output");458 if (st.size > maxBytes) throw new PySandboxError(`Sortie trop volumineuse : ${path.basename(file)} fait ${st.size} octets (maximum ${maxBytes})`, "bad_output");459 const fh = await open(file, FS.O_RDONLY | FS.O_NOFOLLOW);460 try {461 const st2 = await fh.stat();462 if (!st2.isFile() || st2.nlink !== 1 || st2.ino !== st.ino) throw new PySandboxError(`Sortie invalide : ${path.basename(file)} a changé pendant la lecture`, "bad_output");463 if (head === undefined) return await fh.readFile();464 const buf = Buffer.alloc(head);465 const { bytesRead } = await fh.read(buf, 0, head, 0);466 return buf.subarray(0, bytesRead);467 } finally { await fh.close(); }468}469470const PNG_SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);471async function verifyFrames(dir: string, expected: number, width: number, height: number): Promise<void> {472 const st = await lstat(dir).catch(() => null);473 if (!st || !st.isDirectory()) throw new PySandboxError("Sortie invalide : le dossier des trames a disparu ou a été remplacé", "bad_output");474 const names = new Set(Array.from({ length: expected }, (_, i) => `f${String(i).padStart(6, "0")}.png`));475 // Tout ce qui n'est pas une trame attendue est retiré (sans suivre de lien) : le dossier rendu ne contient que des PNG vérifiés.476 for (const name of await readdir(dir)) if (!names.has(name)) await rm(pj(dir, name), { recursive: true, force: true });477 for (const name of names) {478 const head = await readProduced(pj(dir, name), 64 * 1024 * 1024, 26);479 if (head.length < 26 || !head.subarray(0, 8).equals(PNG_SIG) || head.toString("latin1", 12, 16) !== "IHDR") throw new PySandboxError(`Sortie invalide : ${name} n'est pas un PNG`, "bad_output");480 const w = head.readUInt32BE(16), h = head.readUInt32BE(20);481 if (w !== width || h !== height) throw new PySandboxError(`Sortie invalide : ${name} fait ${w}×${h} au lieu de ${width}×${height}`, "bad_output");482 }483}484485const str = (v: unknown, max: number) => (typeof v === "string" && v ? v.slice(0, max) : undefined);486487/**488 * Exécute du Python généré dans le bac à sable.489 * - Résout avec `ok: false` (+ `error`, `traceback`, `checks`) quand le CODE est en cause — exception, résultat non sérialisable ou non fini,490 * invariant de `validate()` non respecté : de quoi nourrir la boucle de correction du modèle.491 * - Lève `PySandboxError` pour le reste : `bad_input` (refus avant exécution), `no_sandbox`, `env_missing`, `timeout`, `memory`,492 * `runtime` (le processus est mort sans rendre de résultat), `bad_output` (sortie absente, falsifiée ou trop volumineuse).493 * Mode `frames` réussi : appeler `cleanup()` une fois les trames consommées.494 */495export async function runPython(o: PyRunOptions): Promise<PyResult> {496 const v = validateInput(o);497 const kernel = hasSandboxExec();498 if (!kernel && !unsafeAllowed()) throw noSandbox();499 const env = await fullEnv();500 const w = await makeWorkDir();501 let keep = false;502 const cleanup = async () => { await removeTree(w.root); };503 try {504 await writeFile(pj(w.input, "scene.py"), o.code, { mode: 0o400 });505 await writeFile(pj(w.input, "params.json"), v.paramsJson, { mode: 0o400 });506 const args = ["--code", pj(w.input, "scene.py"), "--out", w.out, "--mode", o.mode, "--params", pj(w.input, "params.json"),507 ...(o.mode === "frames" ? ["--width", String(v.width), "--height", String(v.height), "--fps", String(v.fps), "--seconds", String(v.seconds)] : []),508 ...(guardsOff() ? ["--no-guard"] : [])];509 const t0 = performance.now();510 const r = await spawnConfined(env, w, args, { timeoutMs: v.timeoutMs, memoryMb: v.memoryMb, kernel });511 const seconds = Math.round(performance.now() - t0) / 1000;512 const sandbox = { kernel, profile: r.profile };513 const line = lastJson(r.stdout);514 const details = { stderr: r.stderr.slice(-4000), stdout: str(line?.stdout, 16_000), traceback: str(line?.traceback, 8000) };515516 if (r.killed === "timeout") throw new PySandboxError(`Délai dépassé : le code Python n'a pas fini en ${v.timeoutMs} ms (boucle sans fin ? calcul trop lourd ?). Processus tué.`, "timeout", details);517 if (r.killed === "memory") throw new PySandboxError(`Mémoire épuisée : le code a dépassé ${v.memoryMb} Mo (pic résident ${r.peakRssMb} Mo). Processus tué. Réduire la taille des tableaux.`, "memory", details);518 if (r.killed === "disk") throw new PySandboxError(`Sortie trop volumineuse : plus de ${DISK_MB} Mo écrits. Processus tué.`, "bad_output", details);519 if (r.killed === "output") throw new PySandboxError(`Sortie standard trop volumineuse (plus de ${MAX_STDOUT_BYTES} octets). Processus tué.`, "bad_output", details);520 if (r.signal === "SIGXCPU") throw new PySandboxError(`Temps processeur épuisé (${Math.ceil(v.timeoutMs / 1000) + 2} s) : calcul trop lourd ou boucle sans fin. Processus tué.`, "timeout", details);521 if (!line || typeof line.ok !== "boolean") {522 const tail = r.stderr.trim().split("\n").filter(Boolean).slice(-3).join(" | ").slice(0, 600);523 throw new PySandboxError(`Le processus Python s'est arrêté sans rendre de résultat (code ${r.code}, signal ${r.signal ?? "aucun"})${tail ? ` : ${tail}` : ""}`, "runtime", details);524 }525 if (line.ok !== true) {526 const error = str(line.error, 2000) ?? "Erreur inconnue dans le code Python";527 if (line.kind === "memory") throw new PySandboxError(error, "memory", details);528 if (line.kind === "input") throw new PySandboxError(error, "bad_input", details);529 return { ok: false, seconds, error, traceback: details.traceback, stdout: details.stdout, sandbox, cleanup: async () => undefined };530 }531 if (line.mode !== o.mode) throw new PySandboxError("Sortie invalide : le résultat annoncé ne correspond pas au mode demandé", "bad_output", details);532533 if (o.mode === "data") {534 let parsed: unknown;535 try { parsed = JSON.parse((await readProduced(pj(w.out, "data.json"), MAX_DATA_BYTES + 4096)).toString("utf8")); }536 catch (e) { if (e instanceof PySandboxError) throw e; throw new PySandboxError("Sortie invalide : data.json n'est pas du JSON strict", "bad_output", details); }537 const p = parsed as { data?: unknown; checks?: unknown } | null;538 if (!p || typeof p !== "object" || !p.data || typeof p.data !== "object" || Array.isArray(p.data) || !Array.isArray(p.checks) || p.checks.some((c) => typeof c !== "string"))539 throw new PySandboxError("Sortie invalide : data.json n'a pas la forme { data: objet, checks: chaînes }", "bad_output", details);540 const checks = (p.checks as string[]).slice(0, 50).map((c) => c.slice(0, 500));541 return { ok: checks.length === 0, data: p.data, checks, seconds, stdout: details.stdout, sandbox, cleanup: async () => undefined,542 ...(checks.length ? { error: `Invariants non respectés (validate) :\n- ${checks.join("\n- ")}` } : {}) };543 }544 const frames = Math.max(1, Math.round(v.seconds * v.fps));545 await verifyFrames(w.out, frames, v.width, v.height);546 keep = true;547 return { ok: true, framesDir: w.out, frames, seconds, stdout: details.stdout, sandbox, cleanup };548 } finally { if (!keep) await cleanup(); }549}550