Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : tests/unit/next-web-sandbox.test.ts9 * Description : pure parts of the runCode sandbox10 * (src/lib/client/sandbox.ts): the frame document (CSP11 * first, no user code, no way to close the script element),12 * console formatting, output clamping, and the shipped13 * runtime executed against a fake global (capture, last14 * value, errors, top-level await, timers, output cap). The15 * isolation itself (opaque origin, CSP, kill on timeout)16 * needs a browser and is asserted by the Playwright suite.17 * Module : tests18 * Repository : https://git.spboucher.ai/note-spboucher-ai19 * Project Website : https://note.spboucher.ai20 * Created : 2026-11-1921 * Last Modified : 2026-11-1922 *23 * Author : Simon-Pierre Boucher24 * Position : Professor of Finance25 * Institution : Université du Québec en Outaouais (UQO)26 * Organization : SP Boucher27 * Website : https://spboucher.ai28 * Git : https://git.spboucher.ai29 *30 * Preferred Contact: contact@spboucher.ai31 * Development : dev@spboucher.ai32 * Support : support@spboucher.ai33 * Security/Admin : admin@spboucher.ai34 *35 * Copyright (c) 202636 * Simon-Pierre Boucher37 * All rights reserved where applicable. This file is governed by the38 * applicable project license, copyright notices and relevant law.39 * Existing third-party rights and notices remain unaffected.40 *41 * License : None specified (no license file in this repository)42 *43 * Do not embed credentials, private keys, access tokens,44 * certificates or confidential personal information.45 *46 * =============================================================================47 * END OF SP BOUCHER SOURCE HEADER48 * =============================================================================49 */5051import { test } from "node:test";52import assert from "node:assert/strict";53import vm from "node:vm";54import { buildSandboxHtml, clampOutput, formatConsoleArgs, newSandboxToken, runSandboxed, sandboxCsp, sandboxRuntimeSource, SANDBOX_ATTRIBUTE, TRUNCATION_MARKER } from "../../src/lib/client/sandbox";5556test("sandbox html: the CSP meta comes before any script and denies everything but the nonce'd bootstrap and blob workers", () => {57 const token = "a1b2c3d4e5f60718293a4b5c6d7e8f90"; const html = buildSandboxHtml(token);58 const meta = html.indexOf('<meta http-equiv="Content-Security-Policy"'); const script = html.indexOf("<script");59 assert.ok(meta > 0 && script > meta, "CSP meta precedes the first script");60 assert.equal(html.indexOf("<meta"), meta, "the CSP is the first meta of the document");61 const csp = /http-equiv="Content-Security-Policy" content="([^"]+)"/.exec(html)![1];62 assert.equal(csp, sandboxCsp(token));63 assert.equal(csp, `default-src 'none'; script-src 'nonce-${token}' 'unsafe-eval'; worker-src blob:; base-uri 'none'; form-action 'none'`);64 for (const forbidden of ["connect-src", "img-src", "frame-src", "'unsafe-inline'", "http:", "https:", "'self'", "*"]) assert.ok(!csp.includes(forbidden), `CSP must not contain ${forbidden}`);65 assert.equal(html.match(/<script/g)!.length, 1, "one script element"); assert.equal(html.match(/<\/script/g)!.length, 1, "nothing inside the bootstrap can close the script element");66 assert.ok(html.includes(`<script nonce="${token}">`)); assert.ok(!html.includes("<!--"));67 assert.ok(!/\bsrc=|href=|<img|<link|<form|<iframe/i.test(html), "the frame document loads nothing");68});69test("sandbox html: static apart from the token — user code is never part of it", () => {70 const a = buildSandboxHtml("0000000000000000aaaaaaaaaaaaaaaa"), b = buildSandboxHtml("1111111111111111bbbbbbbbbbbbbbbb");71 assert.equal(a.replaceAll("0000000000000000aaaaaaaaaaaaaaaa", "T"), b.replaceAll("1111111111111111bbbbbbbbbbbbbbbb", "T"));72 assert.equal(buildSandboxHtml.length, 0, "no parameter for code (the token is optional)");73 assert.ok(!a.includes("__TOKEN__") && !a.includes("__WORKER__"));74 assert.ok(a.includes('d.type === "run"') && a.includes("e.source !== host"), "the code arrives by postMessage from the parent window only");75 assert.ok(a.includes('"*"'), "opaque origin: replies are addressed to window.parent");76 for (const bad of ["", "short", "abc\"><script>alert(1)</script>", "aaaaaaaaaaaaaaaa'bbbb", "aaaaaaaaaaaaaaaa bbbb", "é".repeat(20)]) assert.throws(() => buildSandboxHtml(bad), /Invalid sandbox token/);77 const t = newSandboxToken(); assert.match(t, /^[0-9a-f]{32}$/); assert.notEqual(t, newSandboxToken()); assert.ok(buildSandboxHtml().length > 1000);78});79test("the iframe sandbox attribute is allow-scripts alone", () => {80 assert.equal(SANDBOX_ATTRIBUTE, "allow-scripts");81});82test("runSandboxed outside a browser resolves with an error instead of throwing", async () => {83 const r = await runSandboxed("1 + 1"); assert.deepEqual(r, { text: "Code can only run in a browser", error: true, ms: 0, timedOut: false });84});8586test("formatConsoleArgs: primitives", () => {87 assert.equal(formatConsoleArgs(["a", 1, true, null, undefined]), "a 1 true null undefined");88 assert.equal(formatConsoleArgs([]), ""); assert.equal(formatConsoleArgs([""]), "");89 assert.equal(formatConsoleArgs([10n, -0, NaN, Infinity]), "10n -0 NaN Infinity");90 assert.equal(formatConsoleArgs([12345678901234567890123n]), "12345678901234567890123n");91 assert.equal(formatConsoleArgs([Symbol("s")]), "Symbol(s)");92 assert.equal(formatConsoleArgs([function named() {}, () => {}]), "[Function: named] [Function (anonymous)]");93 assert.equal(formatConsoleArgs(["top"], true), '"top"', "the last-value line quotes strings");94});95test("formatConsoleArgs: objects, arrays, collections", () => {96 assert.equal(formatConsoleArgs([{ a: 1, b: "x", "c-d": [1, "2", null, undefined], e: { f: 2n } }]), '{a: 1, b: "x", "c-d": [1, "2", null, undefined], e: {f: 2n}}');97 assert.equal(formatConsoleArgs([[1, [2, [3]]]]), "[1, [2, [3]]]"); assert.equal(formatConsoleArgs([{}]), "{}"); assert.equal(formatConsoleArgs([[]]), "[]");98 assert.equal(formatConsoleArgs([new Map<unknown, unknown>([["k", 1], [2, { a: 1 }]])]), 'Map(2) {"k" => 1, 2 => {a: 1}}');99 assert.equal(formatConsoleArgs([new Set([1, "a"])]), 'Set(2) {1, "a"}');100 assert.equal(formatConsoleArgs([new Uint8Array([1, 2, 3])]), "Uint8Array(3) [1, 2, 3]");101 assert.equal(formatConsoleArgs([new Date(0)]), "1970-01-01T00:00:00.000Z"); assert.equal(formatConsoleArgs([new Date(NaN)]), "Invalid Date");102 assert.equal(formatConsoleArgs([/a+/gi]), "/a+/gi"); assert.equal(formatConsoleArgs([Promise.resolve(1)]), "Promise {}");103 class Point { x = 1; y = 2; } assert.equal(formatConsoleArgs([new Point()]), "Point {x: 1, y: 2}");104 assert.equal(formatConsoleArgs([Object.create(null)]), "[Object: null prototype] {}");105});106test("formatConsoleArgs: cycles, depth, size and hostile objects never throw", () => {107 const o: any = { name: "o" }; o.self = o; o.list = [o, { back: o }];108 assert.equal(formatConsoleArgs([o]), '{name: "o", self: [Circular], list: [[Circular], {back: [Circular]}]}');109 const shared = { v: 1 }; assert.equal(formatConsoleArgs([{ a: shared, b: shared }]), "{a: {v: 1}, b: {v: 1}}", "a repeated reference is not a cycle");110 assert.equal(formatConsoleArgs([{ a: { b: { c: { d: { e: 1 } } } } }]), "{a: {b: {c: {d: [Object]}}}}");111 assert.equal(formatConsoleArgs([[[[[[1]]]]]]), "[[[[[Array]]]]]");112 const big = formatConsoleArgs([Array.from({ length: 250 }, (_, i) => i)]); assert.ok(big.endsWith(", … 150 more]")); assert.ok(big.length < 600);113 assert.equal(formatConsoleArgs(["x".repeat(20000)]).length, 10001, "very long strings are cut");114 const hostile = { get boom() { throw new Error("no"); }, ok: 1 }; assert.equal(formatConsoleArgs([hostile]), "{boom: [Throws], ok: 1}");115 const proxy = new Proxy({}, { ownKeys() { throw new Error("trap"); }, getPrototypeOf() { throw new Error("trap"); } }); assert.doesNotThrow(() => formatConsoleArgs([proxy]));116 const liar = { toString() { throw new Error("x"); }, get name() { throw new Error("y"); } }; assert.doesNotThrow(() => formatConsoleArgs([liar]));117});118test("formatConsoleArgs: errors", () => {119 assert.equal(formatConsoleArgs([new TypeError("bad")]), "TypeError: bad"); assert.equal(formatConsoleArgs([new Error("")]), "Error");120 assert.equal(formatConsoleArgs([new Error("outer", { cause: new RangeError("inner") })]), "Error: outer [cause: RangeError: inner]");121 assert.equal(formatConsoleArgs([{ e: new Error("in") }]), "{e: Error: in}");122 class MyError extends Error { constructor(m: string) { super(m); this.name = "MyError"; } } assert.equal(formatConsoleArgs(["failed:", new MyError("why")]), "failed: MyError: why");123});124125test("clampOutput", () => {126 assert.equal(clampOutput("short", 10), "short"); assert.equal(clampOutput("", 10), ""); assert.equal(clampOutput("0123456789", 10), "0123456789");127 assert.equal(clampOutput("0123456789A", 10), `0123456789\n${TRUNCATION_MARKER}`);128 assert.equal(clampOutput("abcd\nefgh", 5), `abcd\n${TRUNCATION_MARKER}`, "no blank line before the marker");129 assert.equal(TRUNCATION_MARKER, "… (truncated)");130 const long = "x".repeat(50000); assert.equal(clampOutput(long).length, 20000 + 1 + TRUNCATION_MARKER.length); assert.ok(clampOutput(long).endsWith("… (truncated)"));131 assert.equal(clampOutput("abc", 0).length, 3, "a nonsensical limit falls back to the default"); assert.equal(clampOutput("abc", NaN), "abc");132 assert.equal(clampOutput(undefined as unknown as string, 5), "");133});134135/** Runs the shipped runtime in a separate realm standing in for the worker global (so `console`, timers and globals are the patched ones) and collects what it posts. */136function execute(code: string, maxOutput = 20000, waitMs = 1500): Promise<{ text: string; error: boolean; done: number }> {137 return new Promise((resolve, reject) => {138 let text = ""; let done = 0;139 const context = vm.createContext({140 setTimeout: (f: () => void, ms?: number) => Number(setTimeout(f, ms)), setInterval: (f: () => void, ms?: number) => Number(setInterval(f, ms)), clearTimeout: (id: number) => clearTimeout(id), clearInterval: (id: number) => clearInterval(id),141 console: {}, addEventListener: () => {},142 });143 const scope = vm.runInContext("globalThis", context); const runtime = vm.runInContext(`${sandboxRuntimeSource()}\nspnRuntime`, context);144 const guard = setTimeout(() => reject(new Error(`runtime did not finish: ${JSON.stringify(text)}`)), waitMs);145 runtime(scope, (m: { type: string; text?: string; error?: boolean }) => {146 if (m.type === "out") text += m.text; else if (m.type === "done") { done++; clearTimeout(guard); setTimeout(() => resolve({ text: text.replace(/\n$/, ""), error: !!m.error, done }), 20); }147 }, code, maxOutput);148 });149}150test("runtime: console capture and the value of the last expression", async () => {151 assert.deepEqual(await execute("1 + 1"), { text: "→ 2", error: false, done: 1 });152 assert.deepEqual(await execute('console.log("a", { b: [1] }); console.warn("w"); console.error(new Error("e")); "end"'), { text: 'a {b: [1]}\nw\nError: e\n→ "end"', error: false, done: 1 });153 assert.equal((await execute("const a = 2;\nconst b = 3;\na * b")).text, "→ 6");154 assert.equal((await execute("let s = 0; for (let i = 1; i <= 4; i++) s += i; s")).text, "→ 10");155 assert.equal((await execute("return 5")).text, "→ 5"); assert.equal((await execute("console.log(1)")).text, "1");156 assert.equal((await execute("const x = 1;")).text, ""); assert.equal((await execute("")).text, "");157 assert.equal((await execute("const o = {}; o.o = o; o")).text, "→ {o: [Circular]}");158 assert.equal((await execute("console.assert(1 === 2, 'math'); console.assert(true)")).text, "Assertion failed: math");159});160test("runtime: top-level await, promises and timers are awaited before the run is done", async () => {161 assert.deepEqual(await execute("const v = await Promise.resolve(41); v + 1"), { text: "→ 42", error: false, done: 1 });162 assert.equal((await execute("await new Promise((r) => setTimeout(r, 30)); console.log('after'); 7")).text, "after\n→ 7");163 assert.equal((await execute("setTimeout(() => console.log('late'), 40); console.log('first')")).text, "first\nlate");164 assert.equal((await execute("let n = 0; const id = setInterval(() => { console.log(++n); if (n === 3) clearInterval(id); }, 5); 'started'")).text, '→ "started"\n1\n2\n3');165 assert.equal((await execute("const id = setTimeout(() => console.log('never'), 20); clearTimeout(id); 'ok'")).text, '→ "ok"');166});167test("runtime: syntax errors, exceptions and rejections are reported with error:true and never thrown", async () => {168 const syntax = await execute("let = ;"); assert.equal(syntax.error, true); assert.match(syntax.text, /^SyntaxError: /);169 assert.deepEqual(await execute("console.log('before'); throw new TypeError('boom')"), { text: "before\nUncaught TypeError: boom", error: true, done: 1 });170 assert.deepEqual(await execute("null.x"), { text: (await execute("null.x")).text, error: true, done: 1 }); assert.match((await execute("null.x")).text, /^Uncaught TypeError: /);171 assert.deepEqual(await execute("await Promise.reject(new Error('nope'))"), { text: "Uncaught Error: nope", error: true, done: 1 });172 assert.deepEqual(await execute("throw 'plain'"), { text: "Uncaught plain", error: true, done: 1 });173 assert.deepEqual(await execute("setTimeout(() => { throw new Error('in timer') }, 5); 1"), { text: "→ 1\nUncaught Error: in timer", error: true, done: 1 });174 assert.equal((await execute("setTimeout('alert(1)', 0)")).error, true, "string timers are refused");175});176test("runtime: output is capped at the source and a flood cannot grow without bound", async () => {177 const r = await execute("for (let i = 0; i < 100000; i++) console.log('line ' + i); 'done'", 500);178 assert.equal(r.error, false); assert.ok(r.text.length <= 500 + 64, `capped (${r.text.length})`); assert.ok(r.text.startsWith("line 0\nline 1\n"));179 assert.ok(clampOutput(r.text, 500).endsWith(TRUNCATION_MARKER));180});181182/**183 * Boots the frame document's script in a fake frame realm. `withWorker` gives it a Worker that evaluates the blob in its own realm184 * (as a browser would); without it Worker creation throws and the in-frame fallback must take over.185 */186function bootFrame(token: string, withWorker: boolean) {187 const html = buildSandboxHtml(token); const script = /<script nonce="[0-9a-f]+">([\s\S]*)<\/script>/.exec(html)![1];188 const toParent: any[] = []; const handlers: Record<string, ((e: any) => void)[]> = {}; const host = { postMessage: (m: any, origin: string) => { assert.equal(origin, "*"); toParent.push({ ...m }); /* copied into this realm, as structured clone would */ } };189 const timers = { setTimeout: (f: () => void, ms?: number) => Number(setTimeout(f, ms)), setInterval: (f: () => void, ms?: number) => Number(setInterval(f, ms)), clearTimeout: (id: number) => clearTimeout(id), clearInterval: (id: number) => clearInterval(id) };190 const blobs = new Map<string, string>(); let workers = 0;191 class FakeBlob { text: string; constructor(parts: string[]) { this.text = parts.join(""); } }192 class FakeWorker {193 onmessage: ((e: any) => void) | null = null; onerror: ((e: any) => void) | null = null; private self: any;194 constructor(url: string) {195 if (!withWorker) throw new Error("SecurityError"); workers++;196 const source = blobs.get(url)!; const ctx = vm.createContext({ ...timers, console: {}, addEventListener: () => {}, postMessage: (m: any) => setTimeout(() => this.onmessage?.({ data: m }), 0) });197 this.self = vm.runInContext("globalThis.self = globalThis", ctx); setTimeout(() => vm.runInContext(source, ctx), 0);198 }199 postMessage(m: any) { setTimeout(() => this.self.onmessage?.({ data: m }), 0); }200 terminate() {}201 }202 const context = vm.createContext({ ...timers, console: {}, parent: host, Blob: FakeBlob, Worker: FakeWorker, URL: { createObjectURL: (b: FakeBlob) => { const u = `blob:null/${blobs.size}`; blobs.set(u, b.text); return u; }, revokeObjectURL: () => {} },203 addEventListener: (name: string, fn: (e: any) => void) => { (handlers[name] ??= []).push(fn); } });204 vm.runInContext("globalThis.window = globalThis", context);205 new vm.Script(script); vm.runInContext(script, context);206 const deliver = (data: any, source: any = host) => handlers.message?.forEach((fn) => fn({ data, source }));207 const settle = async (ms = 150) => { await new Promise((r) => setTimeout(r, ms)); return toParent; };208 return { toParent, deliver, settle, host, workers: () => workers, workerSource: () => [...blobs.values()][0] };209}210const outputOf = (messages: any[]) => messages.filter((m) => m.type === "out").map((m) => m.text).join("");211212test("frame bootstrap: valid script, announces ready with the token, accepts a run only from its parent and with the token", async () => {213 const token = "feedfacefeedfacefeedfacefeedface"; const f = bootFrame(token, false);214 assert.deepEqual(f.toParent, [{ spn: token, type: "ready", text: "", error: false }]);215 f.deliver({ spn: "wrongwrongwrongwrongwrongwrong00", type: "run", code: "console.log('bad token')" });216 f.deliver({ spn: token, type: "run", code: "console.log('wrong source')" }, { postMessage() {} });217 f.deliver({ spn: token, type: "run", code: 42 }); f.deliver(null); f.deliver("run");218 assert.equal((await f.settle(60)).length, 1, "nothing ran");219 f.deliver({ spn: token, type: "run", code: "console.log('ok'); 6 * 7", maxOutput: 1000 });220 f.deliver({ spn: token, type: "run", code: "console.log('second run refused')" });221 const messages = await f.settle();222 assert.ok(messages.every((m) => m.spn === token && typeof m.text === "string" && typeof m.error === "boolean"), "every message carries the token and plain fields only");223 assert.deepEqual(messages.map((m) => m.type).filter((t) => t !== "out"), ["ready", "mode", "done"]); assert.equal(messages.find((m) => m.type === "mode").text, "frame", "Worker refused → in-frame fallback");224 assert.equal(outputOf(messages), "ok\n→ 42\n"); assert.equal(messages.at(-1).error, false);225});226test("frame bootstrap: the code runs in a blob Worker when one can be created, and errors come back flagged", async () => {227 const token = "0123456789abcdef0123456789abcdef"; const f = bootFrame(token, true);228 f.deliver({ spn: token, type: "run", code: "console.log(typeof window, typeof self); await new Promise((r) => setTimeout(r, 10)); throw new RangeError('from worker')", maxOutput: 1000 });229 const messages = await f.settle(250);230 assert.equal(f.workers(), 1); assert.equal(messages.find((m) => m.type === "mode").text, "worker");231 assert.equal(outputOf(messages), "undefined object\nUncaught RangeError: from worker\n"); assert.deepEqual(messages.at(-1), { spn: token, type: "done", text: "", error: true });232 assert.doesNotThrow(() => new vm.Script(f.workerSource()), "the worker source is valid JavaScript"); assert.ok(!f.workerSource().includes("from worker"), "the worker blob is static: the code is posted to it");233});234