SPB Git

Repository Public

sandbox.ts 22.2 KB 327 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : src/lib/client/sandbox.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243"use client";44/**45 * file: src/lib/client/sandbox.ts46 * description: executor of the `runCode` block (SPEC §2). The user's JavaScript never runs in the app: each run creates a hidden47 *   `<iframe sandbox="allow-scripts">` (opaque origin: no access to the app's DOM, cookies, localStorage or IndexedDB) whose document48 *   carries its own CSP (`default-src 'none'`: no fetch / XHR / WebSocket / EventSource / images / forms / remote scripts). Inside the49 *   frame the code runs in a Web Worker built from a blob, so an infinite loop cannot freeze the app; the frame itself is the fallback50 *   when a Worker cannot be created. Parent and frame talk through `postMessage` only; the parent accepts messages solely from that51 *   frame's window and carrying the per-run random token. User code is never interpolated into HTML: it is posted once the frame52 *   says it is ready. The promise never rejects because of user code.53 *   The runtime that executes in the frame/worker is kept as source text (it must be self-contained); `formatConsoleArgs` evaluates54 *   that same text lazily so the unit tests exercise exactly what ships. Nothing here does any work at import time.55 * author: Simon-Pierre Boucher — contact@spboucher.ai56 */5758export interface SandboxResult { text: string; error: boolean; ms: number; timedOut: boolean }59export interface SandboxOptions { /** default 5000 */ timeoutMs?: number; /** default 20000 characters */ maxOutput?: number; /** aborting stops the run (the result resolves with error:true) */ signal?: AbortSignal }6061export const SANDBOX_DEFAULT_TIMEOUT_MS = 5000;62export const SANDBOX_DEFAULT_MAX_OUTPUT = 20000;63/** The only token of the iframe `sandbox` attribute. Never add allow-same-origin / allow-top-navigation / allow-popups / allow-forms / allow-modals. */64export const SANDBOX_ATTRIBUTE = "allow-scripts";65export const TRUNCATION_MARKER = "… (truncated)";66/** Time the frame has to load and say "ready" before the run is declared failed (not counted in the user's timeout). */67const BOOT_TIMEOUT_MS = 4000;6869/** CSP of the frame document. The inline bootstrap is allowed by nonce; 'unsafe-eval' lets the runtime compile the user's code; workers only from blob:. */70export const sandboxCsp = (nonce: string) => `default-src 'none'; script-src 'nonce-${nonce}' 'unsafe-eval'; worker-src blob:; base-uri 'none'; form-action 'none'`;7172/**73 * Value formatter shared by console capture and the "last value" line. Plain JavaScript source: it runs inside the worker.74 * spnFormatArgs(args, quoteStrings) → one line of text. Never throws.75 */76const FORMAT_SOURCE = String.raw`77function spnFormatArgs(args, quoteTop) {78  var MAX_DEPTH = 4, MAX_ITEMS = 100, MAX_STRING = 10000;79  function str(s, quote) { if (s.length > MAX_STRING) s = s.slice(0, MAX_STRING) + "…"; return quote ? JSON.stringify(s) : s; }80  function errText(e) {81    var name = "Error", message = "";82    try { name = String(e.name || "Error"); } catch (_) {}83    try { message = String(e.message == null ? "" : e.message); } catch (_) {}84    var out = message ? name + ": " + message : name;85    try { if (e.cause !== undefined) out += " [cause: " + fmt(e.cause, 1, [], true) + "]"; } catch (_) {}86    return out;87  }88  function tagOf(v) { try { return Object.prototype.toString.call(v).slice(8, -1); } catch (_) { return "Object"; } }89  function key(k) { return /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k); }90  function fmt(v, depth, seen, quote) {91    var t = typeof v;92    if (v === null) return "null";93    if (t === "undefined") return "undefined";94    if (t === "string") return str(v, quote);95    if (t === "number") return Object.is(v, -0) ? "-0" : String(v);96    if (t === "boolean") return String(v);97    if (t === "bigint") return String(v) + "n";98    if (t === "symbol") { try { return v.toString(); } catch (_) { return "Symbol()"; } }99    if (t === "function") { var fname = ""; try { fname = String(v.name || ""); } catch (_) {} return fname ? "[Function: " + fname + "]" : "[Function (anonymous)]"; }100    if (seen.indexOf(v) >= 0) return "[Circular]";101    var tag = tagOf(v);102    if (tag === "Error" || v instanceof Error) return errText(v);103    if (tag === "Date") { try { return isNaN(v.getTime()) ? "Invalid Date" : v.toISOString(); } catch (_) { return "Invalid Date"; } }104    if (tag === "RegExp") { try { return String(v); } catch (_) { return "/(?:)/"; } }105    if (tag === "Promise") return "Promise {}";106    if (tag === "WeakMap" || tag === "WeakSet" || tag === "WeakRef") return tag + " {}";107    if (tag === "ArrayBuffer" || tag === "SharedArrayBuffer") { try { return tag + "(" + v.byteLength + ")"; } catch (_) { return tag; } }108    if (depth >= MAX_DEPTH) return Array.isArray(v) ? "[Array]" : "[Object]";109    var next = seen.concat([v]), parts = [], n = 0, more = 0, i;110    if (Array.isArray(v) || (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView(v) && tag !== "DataView")) {111      var len = v.length >>> 0;112      for (i = 0; i < len; i++) { if (n >= MAX_ITEMS) { more = len - n; break; } var item; try { item = fmt(v[i], depth + 1, next, true); } catch (_) { item = "[Throws]"; } parts.push(item); n++; }113      if (more) parts.push("… " + more + " more");114      return (Array.isArray(v) ? "" : tag + "(" + len + ") ") + "[" + parts.join(", ") + "]";115    }116    if (tag === "Map") {117      try { v.forEach(function (val, k) { if (n >= MAX_ITEMS) { more++; return; } parts.push(fmt(k, depth + 1, next, true) + " => " + fmt(val, depth + 1, next, true)); n++; }); } catch (_) { parts.push("[Throws]"); }118      if (more) parts.push("… " + more + " more");119      return "Map(" + (n + more) + ") {" + parts.join(", ") + "}";120    }121    if (tag === "Set") {122      try { v.forEach(function (val) { if (n >= MAX_ITEMS) { more++; return; } parts.push(fmt(val, depth + 1, next, true)); n++; }); } catch (_) { parts.push("[Throws]"); }123      if (more) parts.push("… " + more + " more");124      return "Set(" + (n + more) + ") {" + parts.join(", ") + "}";125    }126    var keys = []; try { keys = Object.keys(v); } catch (_) {}127    for (i = 0; i < keys.length; i++) {128      if (n >= MAX_ITEMS) { more = keys.length - n; break; }129      var val; try { val = fmt(v[keys[i]], depth + 1, next, true); } catch (_) { val = "[Throws]"; }130      parts.push(key(keys[i]) + ": " + val); n++;131    }132    if (more) parts.push("… " + more + " more");133    var cls = ""; try { var proto = Object.getPrototypeOf(v); if (proto === null) cls = "[Object: null prototype] "; else { var c = proto.constructor; if (c && typeof c.name === "string" && c.name && c.name !== "Object") cls = c.name + " "; } } catch (_) {}134    return cls + "{" + parts.join(", ") + "}";135  }136  var out = [];137  for (var a = 0; a < args.length; a++) { var piece; try { piece = fmt(args[a], 0, [], !!quoteTop); } catch (_) { piece = "[Unprintable]"; } out.push(piece); }138  return out.join(" ");139}`;140141/**142 * Runs the user's code in `scope` (a worker global, or the frame's window in fallback mode) and reports through `post`:143 * {type:"out", text} chunks (rate-limited, capped) then exactly one {type:"done", error}. Plain JavaScript source.144 */145const RUNTIME_SOURCE = String.raw`146function spnRuntime(scope, post, code, maxOutput) {147  var cap = (typeof maxOutput === "number" && maxOutput > 0 ? maxOutput : 20000) + 64;148  var buf = "", sent = 0, lastFlush = 0, capped = false, errored = false, pending = 0, mainDone = false, finished = false, live = {};149  var nativeSetTimeout = scope.setTimeout, nativeSetInterval = scope.setInterval, nativeClear = scope.clearTimeout;150  function flush(force) { if (!buf) return; var now = Date.now(); if (!force && now - lastFlush < 50) return; lastFlush = now; var chunk = buf; buf = ""; post({ type: "out", text: chunk }); }151  function emit(line) { if (capped || finished) return; line = String(line); var room = cap - sent; if (line.length + 1 > room) { line = line.slice(0, Math.max(0, room)); capped = true; } sent += line.length + 1; buf += line + "\n"; flush(capped); }152  function describe(e) { try { return spnFormatArgs([e], false); } catch (_) { return "Error"; } }153  function fail(prefix, e) { errored = true; emit(prefix + describe(e)); }154  function finish() { if (finished) return; flush(true); finished = true; post({ type: "done", error: errored }); }155  function check() {156    if (finished || !mainDone || pending > 0) return;157    nativeSetTimeout.call(scope, function () { if (finished || pending > 0) return; nativeSetTimeout.call(scope, function () { if (pending > 0) return; finish(); }, 0); }, 0);158  }159  function guard(fn, args) { try { fn.apply(scope, args); } catch (e) { fail("Uncaught ", e); } }160  scope.setTimeout = function (fn, ms) {161    if (typeof fn !== "function") { fail("", new TypeError("setTimeout needs a function in the sandbox")); return 0; }162    var args = Array.prototype.slice.call(arguments, 2); pending++;163    var id = nativeSetTimeout.call(scope, function () { if (!live[id]) return; delete live[id]; guard(fn, args); pending--; check(); }, ms);164    live[id] = 1; return id;165  };166  scope.setInterval = function (fn, ms) {167    if (typeof fn !== "function") { fail("", new TypeError("setInterval needs a function in the sandbox")); return 0; }168    var args = Array.prototype.slice.call(arguments, 2); pending++;169    var id = nativeSetInterval.call(scope, function () { if (!live[id]) return; guard(fn, args); }, ms);170    live[id] = 1; return id;171  };172  scope.clearTimeout = scope.clearInterval = function (id) { if (live[id]) { delete live[id]; pending--; nativeClear.call(scope, id); check(); } };173  function printer(quote) { return function () { var s; try { s = spnFormatArgs(arguments, quote); } catch (_) { s = "[Unprintable]"; } emit(s); }; }174  var con = scope.console || {}, names = ["log", "info", "debug", "warn", "error", "trace", "table"];175  for (var i = 0; i < names.length; i++) { try { con[names[i]] = printer(false); } catch (_) {} }176  try { con.dir = printer(true); } catch (_) {}177  try { con.assert = function (ok) { if (!ok) { var rest = Array.prototype.slice.call(arguments, 1); emit("Assertion failed" + (rest.length ? ": " + spnFormatArgs(rest, false) : "")); } }; } catch (_) {}178  try { con.clear = function () {}; } catch (_) {}179  try { scope.console = con; } catch (_) {}180  if (scope.addEventListener) {181    scope.addEventListener("error", function (ev) { fail("Uncaught ", ev && (ev.error !== undefined && ev.error !== null ? ev.error : ev.message)); if (ev && ev.preventDefault) ev.preventDefault(); });182    scope.addEventListener("unhandledrejection", function (ev) { fail("Unhandled rejection: ", ev ? ev.reason : undefined); if (ev && ev.preventDefault) ev.preventDefault(); });183  }184  var AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;185  function compile(src) {186    try { return new AsyncFunction("return (" + src + "\n)"); } catch (_) {}187    var trimmed = src.replace(/[\s;]+$/, ""), cut = Math.max(trimmed.lastIndexOf("\n"), trimmed.lastIndexOf(";"));188    if (cut >= 0) {189      var head = trimmed.slice(0, cut + 1), tail = trimmed.slice(cut + 1);190      if (/\S/.test(tail) && !/^\s*(return|throw|var|let|const|if|else|for|while|do|switch|case|default|try|catch|finally|function|async\s+function|class|break|continue|import|export|debugger)\b/.test(tail) && !/^\s*(\}|\/\/|\/\*)/.test(tail)) {191        try { return new AsyncFunction(head + "\nreturn (" + tail + "\n)"); } catch (_) {}192      }193    }194    return new AsyncFunction(src);195  }196  var fn;197  try { fn = compile(String(code == null ? "" : code)); } catch (e) { fail("", e); mainDone = true; check(); return; }198  var run;199  try { run = fn.call(undefined); } catch (e) { fail("Uncaught ", e); mainDone = true; check(); return; }200  run.then(function (v) { if (v !== undefined) emit("→ " + spnFormatArgs([v], true)); }, function (e) { fail("Uncaught ", e); }).then(function () { mainDone = true; check(); });201}`;202203/** Worker script: the runtime in a closure; it announces itself, then runs the single job it receives. */204const WORKER_SOURCE = `(function () {${FORMAT_SOURCE}\n${RUNTIME_SOURCE}205  var send = self.postMessage.bind(self);206  self.onmessage = function (e) { self.onmessage = null; var d = e.data || {}; spnRuntime(self, function (m) { send(m); }, d.code, d.maxOutput); };207  send({ type: "started" });208})();`;209210/** Bootstrap of the frame document. `__TOKEN__` and `__WORKER__` are replaced by buildSandboxHtml. */211const FRAME_SOURCE = String.raw`(function () {212  var TOKEN = "__TOKEN__", WORKER = __WORKER__, host = window.parent, ran = false;213  function send(m) { try { host.postMessage({ spn: TOKEN, type: String(m.type), text: typeof m.text === "string" ? m.text : "", error: !!m.error }, "*"); } catch (_) {} }214  function start(d) {215    if (ran) return; ran = true;216    var worker = null, started = false, fellBack = false, url = null;217    function inFrame() { if (fellBack || started) return; fellBack = true; try { if (worker) worker.terminate(); } catch (_) {} send({ type: "mode", text: "frame" }); spnRuntime(window, send, d.code, d.maxOutput); }218    try {219      url = URL.createObjectURL(new Blob([WORKER], { type: "text/javascript" }));220      worker = new Worker(url);221      worker.onmessage = function (e) {222        var m = e.data; if (!m || typeof m !== "object" || fellBack) return;223        if (m.type === "started") { if (started) return; started = true; try { URL.revokeObjectURL(url); } catch (_) {} send({ type: "mode", text: "worker" }); worker.postMessage({ code: d.code, maxOutput: d.maxOutput }); return; }224        if (!started) return;225        if (m.type === "out" || m.type === "done") send(m);226      };227      worker.onerror = function (e) { if (!started) inFrame(); else if (e && e.preventDefault) e.preventDefault(); };228    } catch (_) { inFrame(); }229  }230  window.addEventListener("message", function (e) { if (e.source !== host) return; var d = e.data; if (!d || typeof d !== "object" || d.spn !== TOKEN) return; if (d.type === "run" && typeof d.code === "string") start(d); });231  send({ type: "ready" });232})();`;233234const NONCE_RE = /^[A-Za-z0-9]{16,64}$/;235/** 128 random bits as hex: the per-run token (message authentication) and the CSP nonce of the frame's bootstrap script. */236export function newSandboxToken(): string {237  const bytes = new Uint8Array(16); crypto.getRandomValues(bytes);238  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");239}240/** Makes a JavaScript string literal that cannot close the surrounding <script> element or open an HTML comment. */241const inlineLiteral = (source: string) => JSON.stringify(source).replace(/</g, "\\u003c").replace(/[\u2028\u2029]/g, (c) => (c.charCodeAt(0) === 0x2028 ? "\\u2028" : "\\u2029"));242243/**244 * The frame document. Static apart from the token: it never contains user code. The CSP <meta> is the first element of <head>,245 * before any script, so the policy applies to everything the document (and the worker it creates) does.246 */247export function buildSandboxHtml(nonce: string = newSandboxToken()): string {248  if (!NONCE_RE.test(nonce)) throw new Error("Invalid sandbox token");249  const boot = FRAME_SOURCE.replace("__TOKEN__", nonce).replace("__WORKER__", () => inlineLiteral(WORKER_SOURCE));250  return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${sandboxCsp(nonce)}"><meta charset="utf-8"><title>sandbox</title></head><body><script nonce="${nonce}">${FORMAT_SOURCE}\n${RUNTIME_SOURCE}\n${boot}</script></body></html>`;251}252253let formatter: ((args: unknown[], quote: boolean) => string) | null = null;254/**255 * `console.log`-style formatting of a list of values (strings raw, objects inspected, cycles and errors safe), exactly as the sandbox256 * does it: the shipped formatter source is evaluated on first call. Used by the unit tests; the app itself never needs to call it.257 */258export function formatConsoleArgs(args: unknown[], quoteStrings = false): string {259  formatter ??= new Function(`${FORMAT_SOURCE}\nreturn spnFormatArgs;`)() as (args: unknown[], quote: boolean) => string;260  return formatter(args, quoteStrings);261}262/** Source of the runtime (`spnFormatArgs` + `spnRuntime`) exactly as shipped to the frame and its worker: the tests evaluate it in an isolated realm. */263export const sandboxRuntimeSource = (): string => `${FORMAT_SOURCE}\n${RUNTIME_SOURCE}`;264265/** Limits `text` to `max` characters; a marker line says so when something was cut. */266export function clampOutput(text: string, max: number = SANDBOX_DEFAULT_MAX_OUTPUT): string {267  const limit = Number.isFinite(max) && max > 0 ? Math.floor(max) : SANDBOX_DEFAULT_MAX_OUTPUT;268  const s = typeof text === "string" ? text : String(text ?? "");269  if (s.length <= limit) return s;270  return `${s.slice(0, limit).replace(/\n$/, "")}\n${TRUNCATION_MARKER}`;271}272const seconds = (ms: number) => { const s = ms / 1000; return Number.isInteger(s) ? String(s) : s.toFixed(1); };273274/**275 * Runs `code` (JavaScript) in a throw-away sandboxed frame and resolves with what it printed. Must be called from an explicit user276 * action. Resolves — never rejects — for syntax errors, exceptions, timeouts and sandbox start failures (`error: true`).277 */278export function runSandboxed(code: string, opts: SandboxOptions = {}): Promise<SandboxResult> {279  const timeoutMs = Number.isFinite(opts.timeoutMs) && (opts.timeoutMs as number) > 0 ? (opts.timeoutMs as number) : SANDBOX_DEFAULT_TIMEOUT_MS;280  const maxOutput = Number.isFinite(opts.maxOutput) && (opts.maxOutput as number) > 0 ? Math.floor(opts.maxOutput as number) : SANDBOX_DEFAULT_MAX_OUTPUT;281  return new Promise<SandboxResult>((resolve) => {282    if (typeof document === "undefined" || typeof window === "undefined") return resolve({ text: "Code can only run in a browser", error: true, ms: 0, timedOut: false });283    if (opts.signal?.aborted) return resolve({ text: "Stopped", error: true, ms: 0, timedOut: false });284    const token = newSandboxToken();285    const iframe = document.createElement("iframe");286    iframe.setAttribute("sandbox", SANDBOX_ATTRIBUTE);287    iframe.setAttribute("aria-hidden", "true"); iframe.setAttribute("tabindex", "-1"); iframe.setAttribute("title", "Code sandbox");288    iframe.setAttribute("referrerpolicy", "no-referrer"); iframe.setAttribute("allow", "");289    iframe.setAttribute("data-spn-sandbox", "");290    iframe.style.cssText = "position:fixed;left:-9999px;top:0;width:1px;height:1px;border:0;opacity:0;pointer-events:none;visibility:hidden";291    let text = ""; let settled = false; let startedAt = 0; let bootTimer: ReturnType<typeof setTimeout> | null = null; let runTimer: ReturnType<typeof setTimeout> | null = null;292    const elapsed = () => (startedAt ? Math.max(0, Math.round(performance.now() - startedAt)) : 0);293    const withLine = (line: string) => { const body = clampOutput(text.replace(/\n+$/, ""), maxOutput); return body ? `${body}\n${line}` : line; };294    const finish = (r: SandboxResult) => {295      if (settled) return; settled = true;296      if (bootTimer) clearTimeout(bootTimer); if (runTimer) clearTimeout(runTimer);297      window.removeEventListener("message", onMessage); opts.signal?.removeEventListener("abort", onAbort);298      // Removing the frame destroys its document and terminates the worker it owns, even one stuck in an infinite loop.299      iframe.remove();300      resolve(r);301    };302    const onAbort = () => finish({ text: withLine("Stopped"), error: true, ms: elapsed(), timedOut: false });303    function onMessage(e: MessageEvent) {304      if (settled || e.source !== iframe.contentWindow || e.source === null) return;305      const d = e.data as { spn?: unknown; type?: unknown; text?: unknown; error?: unknown } | null;306      if (!d || typeof d !== "object" || d.spn !== token) return;307      if (d.type === "ready") {308        if (startedAt) return;309        if (bootTimer) { clearTimeout(bootTimer); bootTimer = null; }310        startedAt = performance.now();311        runTimer = setTimeout(() => finish({ text: withLine(`Timed out after ${seconds(timeoutMs)} s`), error: true, ms: elapsed(), timedOut: true }), timeoutMs);312        // The frame's origin is opaque ("null"), so the target origin cannot be named; the recipient is this very window object.313        iframe.contentWindow?.postMessage({ spn: token, type: "run", code: String(code ?? ""), maxOutput }, "*");314      } else if (d.type === "out") {315        if (startedAt && typeof d.text === "string" && text.length <= maxOutput) text += d.text.slice(0, maxOutput + 1 - text.length);316      } else if (d.type === "done") {317        if (startedAt) finish({ text: clampOutput(text.replace(/\n+$/, ""), maxOutput), error: d.error === true, ms: elapsed(), timedOut: false });318      }319    }320    window.addEventListener("message", onMessage);321    opts.signal?.addEventListener("abort", onAbort);322    bootTimer = setTimeout(() => finish({ text: "The sandbox could not start", error: true, ms: 0, timedOut: false }), BOOT_TIMEOUT_MS);323    try { iframe.srcdoc = buildSandboxHtml(token); (document.body ?? document.documentElement).appendChild(iframe); }324    catch { finish({ text: "The sandbox could not start", error: true, ms: 0, timedOut: false }); }325  });326}327
Files main
Menu

Theme