master
AdityaAngajala v0.12.8 160fd3c
// adom/adom-3d-viewer#5 (John): the viewer must come up inside the wiki's
// sandboxed widget frame. That frame is an OPAQUE origin (sandbox without
// allow-same-origin: every storage access throws) under the wiki's widget
// CSP (connect-src 'self' data:, no blob:), so this test builds exactly that:
// an https server (the CSP allows script-src https: only) that serves the
// built bundle, a tiny GLB and a harness page carrying the wiki CSP header,
// framed with sandbox="allow-scripts" by an outer page. Headless Chrome with
// SwiftShader renders it; the checks are the ones the issue asks for: a
// ready report that says ok, the loading overlay dismissed, the environment
// map ready with no blob URL, ephemeral storage, no CSP violation, painted
// chip pixels in the canvas, then destroy/recreate three times.
//
// Bounded: every wait has a deadline; the whole run is capped at 120 s.
import http from "node:http";
import https from "node:https";
import { execSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve, extname } from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const DIST = join(ROOT, process.env.VIEWER_DIST || "dist-standalone");
const require = createRequire(import.meta.url);
const deadline = Date.now() + 120_000;
let passed = 0, failed = 0;
const failures = [];
function assert(cond, msg) { if (cond) { passed++; console.log("    ok " + msg); } else { failed++; failures.push(msg); console.log("    FAIL " + msg); } }
function section(t) { console.log("\n  [" + t + "]"); }

// The wiki's widget-frame CSP (git-wiki lib/router.js sandboxedHtmlCspParts
// with wasm: true and no registry origin). Read from the sibling checkout
// when present so drift is caught; the literal is the 2026-09-10 value.
const WIKI_CSP_LITERAL = [
  "sandbox allow-scripts allow-downloads allow-popups allow-popups-to-escape-sandbox",
  "default-src 'none'",
  "script-src 'unsafe-inline' 'wasm-unsafe-eval' https:",
  "style-src 'unsafe-inline' https:",
  "img-src data: https:",
  "media-src data: https:",
  "font-src data: https:",
  "frame-src https:",
  "connect-src 'self' data:",
  "form-action 'none'",
  "object-src 'none'",
  "base-uri 'none'",
].join("; ");
let WIKI_CSP = WIKI_CSP_LITERAL;
try {
  const routerPath = resolve(ROOT, "..", "git-wiki", "lib", "router.js");
  if (existsSync(routerPath)) {
    const { sandboxedHtmlCsp } = await import(routerPath);
    WIKI_CSP = sandboxedHtmlCsp([], { wasm: true });
    if (WIKI_CSP !== WIKI_CSP_LITERAL) console.log("  note: the wiki CSP differs from this test's literal; using the wiki's:\n  " + WIKI_CSP);
  }
} catch { /* the literal stands */ }

// A minimal GLB: one unit box (24 vertices, 36 indices), so a painted
// scene has real geometry in the middle of the canvas.
function makeBoxGlb() {
  const pos = [], idx = [];
  const faces = [
    [[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]], [[1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, -1]],
    [[-1, 1, 1], [1, 1, 1], [1, 1, -1], [-1, 1, -1]], [[-1, -1, -1], [1, -1, -1], [1, -1, 1], [-1, -1, 1]],
    [[1, -1, 1], [1, -1, -1], [1, 1, -1], [1, 1, 1]], [[-1, -1, -1], [-1, -1, 1], [-1, 1, 1], [-1, 1, -1]],
  ];
  faces.forEach((f, fi) => { f.forEach(v => pos.push(v[0] * 0.01, v[1] * 0.01, v[2] * 0.01)); const b = fi * 4; idx.push(b, b + 1, b + 2, b, b + 2, b + 3); });
  const posBuf = Buffer.from(new Float32Array(pos).buffer);
  const idxBuf = Buffer.from(new Uint16Array(idx).buffer);
  const bin = Buffer.concat([posBuf, idxBuf, Buffer.alloc((4 - (idxBuf.length % 4)) % 4)]);
  const json = {
    asset: { version: "2.0" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: "chip_body" }],
    meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }],
    materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.9, 0.55, 0.1, 1], metallicFactor: 0.2, roughnessFactor: 0.5 } }],
    buffers: [{ byteLength: bin.length }],
    bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: posBuf.length }, { buffer: 0, byteOffset: posBuf.length, byteLength: idxBuf.length }],
    accessors: [{ bufferView: 0, componentType: 5126, count: pos.length / 3, type: "VEC3", min: [-0.01, -0.01, -0.01], max: [0.01, 0.01, 0.01] },
      { bufferView: 1, componentType: 5123, count: idx.length, type: "SCALAR" }],
  };
  let jsonBuf = Buffer.from(JSON.stringify(json)); jsonBuf = Buffer.concat([jsonBuf, Buffer.alloc((4 - (jsonBuf.length % 4)) % 4, 0x20)]);
  const header = Buffer.alloc(12); header.write("glTF", 0); header.writeUInt32LE(2, 4); header.writeUInt32LE(12 + 8 + jsonBuf.length + 8 + bin.length, 8);
  const ch = (len, type) => { const b = Buffer.alloc(8); b.writeUInt32LE(len, 0); b.write(type, 4); return b; };
  return Buffer.concat([header, ch(jsonBuf.length, "JSON"), jsonBuf, ch(bin.length, "BIN\0"), bin]);
}
const GLB = makeBoxGlb();

// The harness that runs INSIDE the sandboxed frame. It talks to the test
// only through window globals puppeteer reads from the frame's context.
const HARNESS = `<!doctype html><html><head><meta charset="utf-8">
<style>html,body{margin:0;height:100%;background:#000}#wrap{position:relative;width:640px;height:400px}</style>
</head><body><div id="wrap"></div>
<script type="module">
  window.__log = [];
  window.__viol = [];
  document.addEventListener('securitypolicyviolation', e => window.__viol.push((e.effectiveDirective || '?') + ' ' + (e.blockedURI || '?')));
  const orig = console.error; console.error = (...a) => { window.__log.push(a.map(String).join(' ')); orig(...a); };
  let storageThrows = false; try { window.localStorage.getItem('x'); } catch (e) { storageThrows = true; }
  window.__storageThrows = storageThrows;
  await import('/adom-3d-viewer-babylon9.esm.js');
  window.__runs = [];
  window.__create = async function(useBytes) {
    const wrap = document.getElementById('wrap');
    const opts = { zUp: true, showViewCube: true, showGround: false };
    if (!useBytes) opts.modelUrl = '/chip.glb';
    const v = window.Adom3DViewerBabylon9.init(wrap, opts);
    if (useBytes) { const bytes = new Uint8Array(await (await fetch('/chip.glb')).arrayBuffer()); await v.whenReady(); await v.loadModelBytes(bytes, { extension: '.glb' }); }
    const report = await v.whenReady();
    // paint check: sample the canvas center for pixels that are neither the
    // gradient background nor black
    const canvas = wrap.querySelector('canvas');
    let painted = 0, total = 0;
    try {
      const url = await v.captureScreenshot({ width: 320, height: 200 });
      const img = new Image(); await new Promise((r, j) => { img.onload = r; img.onerror = j; img.src = url; });
      const c = document.createElement('canvas'); c.width = 320; c.height = 200; const ctx = c.getContext('2d'); ctx.drawImage(img, 0, 0);
      const d = ctx.getImageData(100, 60, 120, 80).data;
      for (let i = 0; i < d.length; i += 4) { total++; const r = d[i], g = d[i+1], b = d[i+2]; if (r > 120 && g > 60 && b < 90) painted++; }
    } catch (e) { window.__log.push('paint check failed: ' + e); }
    const overlay = !!wrap.querySelector('#babylonjsLoadingDiv');
    const out = { report, painted, total, overlay, hasCanvas: !!canvas };
    window.__runs.push(out);
    window.__viewer = v;
    return out;
  };
  window.__destroy = function() { try { window.__viewer.destroy(); } catch (e) { window.__log.push('destroy threw: ' + e); } window.__viewer = null; document.getElementById('wrap').innerHTML = ''; };
  window.__harnessReady = true;
</script></body></html>`;

const OUTER = (port) => `<!doctype html><html><body style="margin:0"><iframe id="f" sandbox="allow-scripts" src="https://localhost:${port}/harness.html" style="width:660px;height:420px;border:0"></iframe></body></html>`;

// self-signed cert for the https origin the CSP requires
const certDir = mkdtempSync(join(tmpdir(), "viewer-sandbox-"));
execSync(`openssl req -x509 -newkey rsa:2048 -nodes -keyout ${certDir}/key.pem -out ${certDir}/cert.pem -days 2 -subj "/CN=localhost" 2>/dev/null`);
const MIME = { ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".wasm": "application/wasm", ".glb": "model/gltf-binary", ".html": "text/html; charset=utf-8" };
let port = 0;
const server = https.createServer({ key: readFileSync(join(certDir, "key.pem")), cert: readFileSync(join(certDir, "cert.pem")) }, (req, res) => {
  const url = new URL(req.url, "https://localhost");
  if (url.pathname === "/harness.html") { res.writeHead(200, { "Content-Type": MIME[".html"], "Content-Security-Policy": WIKI_CSP, "Cache-Control": "no-store" }); return res.end(HARNESS); }
  if (url.pathname === "/outer.html") { res.writeHead(200, { "Content-Type": MIME[".html"] }); return res.end(OUTER(port)); }
  // An opaque origin fetches module scripts in CORS mode: the wiki's static
  // route answers with Access-Control-Allow-Origin: *, so this server does too.
  if (url.pathname === "/chip.glb") { res.writeHead(200, { "Content-Type": MIME[".glb"], "Access-Control-Allow-Origin": "*" }); return res.end(GLB); }
  const file = join(DIST, url.pathname.replace(/^\/+/, ""));
  if (!file.startsWith(DIST) || !existsSync(file)) { res.writeHead(404); return res.end("nope"); }
  res.writeHead(200, { "Content-Type": MIME[extname(file)] || "application/octet-stream", "X-Content-Type-Options": "nosniff", "Access-Control-Allow-Origin": "*" });
  res.end(readFileSync(file));
});
await new Promise(r => server.listen(0, "127.0.0.1", r));
port = server.address().port;

let puppeteer;
try { puppeteer = (await import("puppeteer-core")).default; }
catch { puppeteer = (await import(resolve(ROOT, "..", "node_modules", "puppeteer-core", "lib", "puppeteer", "puppeteer-core.js"))).default; }
function findChrome() {
  const env = process.env.PUPPETEER_EXECUTABLE_PATH; if (env && existsSync(env)) return env;
  const base = join(process.env.HOME || "", ".cache", "puppeteer", "chrome");
  if (existsSync(base)) for (const d of readdirSyncSafe(base)) { const p = join(base, d, "chrome-linux64", "chrome"); if (existsSync(p)) return p; }
  for (const p of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) if (existsSync(p)) return p;
  throw new Error("no Chrome found; set PUPPETEER_EXECUTABLE_PATH");
}
function readdirSyncSafe(d) { try { return require("node:fs").readdirSync(d); } catch { return []; } }
const browser = await puppeteer.launch({
  executablePath: findChrome(), headless: true,
  args: ["--no-sandbox", "--ignore-certificate-errors", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--disable-gpu-sandbox"],
});
try {
  section("the bundle boots in an opaque-origin frame under the wiki CSP");
  const page = await browser.newPage();
  const pageErrors = [];
  page.on("pageerror", e => pageErrors.push(String(e && e.message || e)));
  await page.goto(`https://localhost:${port}/outer.html`, { waitUntil: "load" });
  const frame = page.frames().find(f => f.url().includes("/harness.html"));
  assert(frame, "the sandboxed harness frame exists");
  await frame.waitForFunction("window.__harnessReady === true", { timeout: 30_000 });
  assert(await frame.evaluate(() => window.__storageThrows), "the frame really is opaque-origin: localStorage throws");
  assert(await frame.evaluate(() => typeof window.Adom3DViewerBabylon9 === "object" && typeof window.Adom3DViewerBabylon9.init === "function"), "bundle loaded (script-src https: satisfied)");
  const version = await frame.evaluate(() => window.Adom3DViewerBabylon9.version);
  assert(version === readFileSync(join(ROOT, "VERSION"), "utf8").trim(), `runtime version matches VERSION (${version})`);

  section("first viewer: ready report, overlay down, environment from memory, painted chip");
  const r1 = await frame.evaluate(() => window.__create(false));
  const rep = r1.report;
  assert(rep && rep.ok === true, `report.ok (${JSON.stringify(rep && rep.hints)})`);
  assert(rep.environment.source === "bundled-studio" && rep.environment.ready === true, `environment ready from the bundled bytes (${JSON.stringify(rep.environment)})`);
  assert(rep.storage === "ephemeral", "storage reported ephemeral");
  assert(rep.hints.some(h => h.code === "STORAGE_EPHEMERAL"), "the ephemeral storage hint names it");
  assert(rep.loadingOverlay === "hidden" && r1.overlay === false, "loading overlay dismissed");
  assert(rep.model.loaded && rep.model.meshes >= 1 && rep.model.vertices === 24, `model loaded (${rep.model.meshes} mesh, ${rep.model.vertices} vertices)`);
  assert(rep.cspViolations.length === 0, `no CSP violation recorded by the viewer (${JSON.stringify(rep.cspViolations)})`);
  const viol = await frame.evaluate(() => window.__viol);
  assert(viol.length === 0, `no securitypolicyviolation in the frame (${viol.join(" | ")})`);
  assert(rep.camera.ready && rep.camera.mode === "perspective", "camera ready in perspective");
  assert(r1.hasCanvas, "a canvas is in the frame");
  assert(r1.painted > r1.total * 0.05, `chip pixels painted in the center (${r1.painted}/${r1.total})`);
  const errs = await frame.evaluate(() => window.__log);
  assert(!errs.some(l => /SecurityError|blob:|Refused to/.test(l)), `no storage/blob/CSP errors logged (${errs.slice(0, 3).join(" | ")})`);

  section("destroy and recreate, three times, alternating URL and bytes transport");
  for (let i = 0; i < 3; i++) {
    await frame.evaluate(() => window.__destroy());
    const gone = await frame.evaluate(() => !document.querySelector("#wrap canvas") && !document.querySelector("#babylonjsLoadingDiv"));
    assert(gone, `run ${i + 1}: destroy removed the canvas and any overlay`);
    const r = await frame.evaluate((useBytes) => window.__create(useBytes), i % 2 === 0);
    assert(r.report.ok === true, `run ${i + 1}: report.ok (${JSON.stringify(r.report.hints)})`);
    assert(r.report.model.loaded && r.report.model.vertices === 24, `run ${i + 1}: model loaded via ${i % 2 === 0 ? "bytes" : "url"}`);
    assert(r.overlay === false, `run ${i + 1}: overlay dismissed`);
    assert(r.painted > r.total * 0.05, `run ${i + 1}: chip painted (${r.painted}/${r.total})`);
    if (Date.now() > deadline) { assert(false, "deadline exceeded"); break; }
  }
  assert(pageErrors.length === 0, `no uncaught page errors (${pageErrors.slice(0, 2).join(" | ")})`);
} finally {
  await browser.close();
  server.close();
}
console.log(`\n${passed} passed, ${failed} failed`);
if (failed) { console.log("Failures:"); for (const f of failures) console.log("  - " + f); }
process.exit(failed ? 1 : 0);