Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.
// T3 (THIET-KE gói mẫu §3.3): cảnh thử gọi mạng không tới được đâu; preview chạy qua tool Bash của Claude bị jail chặn.
// node packs/test/t3-network.mjs (cả 2 phần; phần B gọi Claude Code, model haiku)
// node packs/test/t3-network.mjs --no-claude
// Phần A: máy chủ cục bộ A đếm kết nối; cảnh gọi fetch / new Image().src / WebSocket / sendBeacon / XHR / CSS url() / import() /
// location= / window.open / iframe / link tới A. Mốc so (không khoá) phải đếm > 0; đúng cấu hình engine: A = 0.
// Internet công khai: cảnh tải 1 ảnh http + 1 ảnh https thật, đọc màu ô cờ trên khung chụp (cần máy có mạng).
// Phần B: Claude (chạy khoá) gọi `node ../../engine/preview.mjs ../other -o ../../x.jpg` → thoát mã 2 (env LUMREELS_JAIL
// được tiến trình con của tool Bash thừa hưởng); `… scene -o preview.jpg` vẫn chạy.
import fs from 'node:fs';
import path from 'node:path';
import { check, info, done, counterServer, minimalScene, makeTestJob, readStream, ROOT } from './helpers.mjs';
import { runHF, syncLib, run } from '../../engine/lib.mjs';
import { preview } from '../../engine/preview.mjs';
import { render } from '../../engine/render.mjs';
import { injectCsp, offlineEnv } from '../../engine/sandbox.mjs';
import { runClaude } from '../../generator/claude.mjs';
const noClaude = process.argv.includes('--no-claude');
const keep = process.argv.includes('--keep');
const PUB = 'http://example.com'; // tên miền công khai (chỉ để có yêu cầu ra ngoài lẫn trong cảnh)
function probeScene(port, { nav = false } = {}) {
const A = `http://127.0.0.1:${port}`;
const body = nav
? `<script>var A = ${JSON.stringify(A)}, P = ${JSON.stringify(PUB)};
try { window.open(A + '/popup'); } catch (e) {}
try { var f = document.createElement('iframe'); document.body.appendChild(f); frames[0].open(A + '/frame-popup'); } catch (e) {}
try { var f2 = document.createElement('iframe'); document.body.appendChild(f2); f2.contentWindow.location = A + '/frame-nav'; } catch (e) {}
try { var a = document.createElement('a'); a.href = A + '/link'; document.body.appendChild(a); a.click(); } catch (e) {}
setTimeout(function(){ try { location.href = A + '/nav'; } catch (e) {} }, 30);
setTimeout(function(){ try { location.assign(P + '/nav'); } catch (e) {} }, 400);</script>`
: `<div style="position:absolute;left:0;top:0;width:10px;height:10px;background-image:url(${A}/css-bg)"></div>
<script>
(function(){
var A = ${JSON.stringify(A)}, P = ${JSON.stringify(PUB)};
function q(f){ try { f(); } catch (e) {} }
q(function(){ fetch(A + '/fetch').catch(function(){}); });
q(function(){ fetch(P + '/fetch').catch(function(){}); });
q(function(){ new Image().src = A + '/img'; });
q(function(){ new Image().src = P + '/img'; });
q(function(){ var w = new WebSocket('ws://127.0.0.1:${port}/ws'); w.onerror = function(){}; });
q(function(){ var w = new WebSocket('ws://example.com/ws'); w.onerror = function(){}; });
q(function(){ navigator.sendBeacon(A + '/beacon', 'x'); });
q(function(){ var x = new XMLHttpRequest(); x.open('GET', A + '/xhr'); x.send(); });
q(function(){ import(A + '/mod.js').catch(function(){}); });
q(function(){ var s = document.createElement('script'); s.src = P + '/s.js'; document.head.appendChild(s); });
q(function(){ var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = A + '/css'; document.head.appendChild(l); });
q(function(){ var i = document.createElement('img'); i.src = A + '/img-tag'; document.body.appendChild(i); });
})();
</script>`;
return minimalScene({ body });
}
/**
* Cảnh dò đường "chèn bằng chuỗi HTML / nút từ nơi khác" (lỗ còn hở sau P0): mỗi đường gọi 1 path riêng tới máy chủ A
* qua popup (frames[i].open, <a target=_blank>, document.open 3 đối số). Không khoá thì A đếm được từng path.
*/
const HTML_VECTORS = ['ih-frame', 'iah-onload', 'oh-frame', 'dp-frame', 'dw-frame', 'ih-link', 'det-link', 'ccf-link', 'dopen', 'range-frame', 'clone-link', 'srh-frame', 'adopt-link'];
function htmlVectorScene(port, { write = true } = {}) {
const A = `http://127.0.0.1:${port}`;
return minimalScene({ body: `<script>var A = ${JSON.stringify(A)};
function q(f){ try { f(); } catch (e) {} }
function last(){ return window.frames[window.frames.length - 1]; }
function box(){ var d = document.createElement('div'); document.body.appendChild(d); return d; }
// 1. innerHTML chèn iframe rồi mở popup từ cửa sổ của iframe
q(function(){ box().innerHTML = '<iframe></iframe>'; last().open(A + '/ih-frame'); });
// 2. insertAdjacentHTML: iframe có onload (chạy ngay lúc chèn)
q(function(){ window.IAH = A + '/iah-onload'; box().insertAdjacentHTML('beforeend', '<iframe onload="try{window.frames[window.frames.length-1].open(window.IAH)}catch(e){}"></iframe>'); });
// 3. outerHTML
q(function(){ var s = document.createElement('span'); document.body.appendChild(s); s.outerHTML = '<iframe></iframe>'; last().open(A + '/oh-frame'); });
// 4. DOMParser rồi appendChild
q(function(){ var d = new DOMParser().parseFromString('<iframe></iframe>', 'text/html'); var f = d.body.firstChild || d.createElement('iframe'); document.body.appendChild(document.adoptNode(f)); last().open(A + '/dp-frame'); });
// 6. innerHTML chèn <a target=_blank> rồi click
q(function(){ var d = box(); d.innerHTML = '<a target="_blank" href="' + A + '/ih-link">x</a>'; d.firstChild.click(); });
// 7. <a> tách rời, đặt target sau khi tạo, click
q(function(){ var a = document.createElement('a'); a.href = A + '/det-link'; a.setAttribute('target', '_blank'); a.click(); });
// 8. createContextualFragment: <a target> nằm trong fragment chưa chèn
q(function(){ var f = document.createRange().createContextualFragment('<a target="_blank" href="' + A + '/ccf-link">x</a>'); f.firstChild.click(); });
// 9. document.open 3 đối số = window.open
q(function(){ document.open(A + '/dopen', '_blank', ''); });
// 10. Range.insertNode với iframe lấy từ DOMParser
q(function(){ var d = new DOMParser().parseFromString('<iframe></iframe>', 'text/html'); var r = document.createRange(); r.selectNodeContents(box()); r.insertNode(d.body.firstChild); last().open(A + '/range-frame'); });
// 11. cloneNode của 1 <a> trong trang (bản sao tách rời, không mang theo bộ chặn click), đặt target, click
q(function(){ var d = box(); d.innerHTML = '<a href="' + A + '/clone-link">x</a>'; var c = d.firstChild.cloneNode(true); c.setAttribute('target', '_blank'); c.click(); });
// 12. shadowRoot.innerHTML
q(function(){ var h = box(); var r = h.attachShadow({ mode: 'open' }); r.innerHTML = '<iframe></iframe>'; last().open(A + '/srh-frame'); });
// 13. <a> của tài liệu DOMParser, adoptNode sang tài liệu này (không chèn), đặt target, click
q(function(){ var d = new DOMParser().parseFromString('<a href="' + A + '/adopt-link">x</a>', 'text/html'); var a = document.adoptNode(d.body.firstChild); a.setAttribute('target', '_blank'); a.click(); });
</script>${write ? `
<script>
// 5. document.write lúc đang phân tích trang (HyperFrames không dựng được cảnh có document.write, kể cả khi không khoá:
// chỉ dùng ở vòng đếm kết nối, không dùng ở vòng preview)
try { document.write('<iframe></iframe>'); window.frames[window.frames.length - 1].open(A + '/dw-frame'); } catch (e) {}
</script>` : ''}` });
}
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
/** Cảnh dò Internet công khai: tải 1 ảnh http/https công khai; tải được → ô (100,100) đỏ, lỗi → xanh lá. */
function publicProbeScene(url) {
return minimalScene({ body: `<div id="flag" style="position:absolute;left:0;top:0;width:200px;height:200px;background:#888"></div>
<script>var i = new Image(); i.onload = function(){ document.getElementById('flag').style.background = '#f00'; };
i.onerror = function(){ document.getElementById('flag').style.background = '#0f0'; }; i.src = ${JSON.stringify(url.slice(0, 2))} + ${JSON.stringify(url.slice(2))};</script>` });
}
async function pixelAt(png) {
const r = await run('ffmpeg', ['-v', 'error', '-i', png, '-vf', 'crop=1:1:100:100', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { encoding: 'latin1' });
const b = Buffer.from(r.out, 'latin1');
return b[0] > 200 && b[1] < 60 ? 'tải được' : b[1] > 200 && b[0] < 60 ? 'bị chặn' : 'không rõ';
}
async function partA() {
console.log('== Phần A: cảnh không ra mạng');
const A = await counterServer();
const jobs = [];
try {
const mk = (tag, html) => { const j = makeTestJob(`t3-${tag}`, html); jobs.push(j); syncLib(path.join(j.dir, 'scene')); return j; };
const snap = async (j, { csp, env, at = '0,1,2' }) => {
const scene = path.join(j.dir, 'scene');
const file = path.join(scene, 'index.html');
const orig = fs.readFileSync(file, 'utf8');
if (csp) fs.writeFileSync(file, injectCsp(orig));
const out = path.join(scene, '.hyperframes', 'snap');
fs.rmSync(out, { recursive: true, force: true });
try {
await runHF(['snapshot', scene, '--at', at, '--no-end', '-o', out, '--json'], { cwd: scene, env });
return fs.existsSync(out) ? fs.readdirSync(out).filter((f) => f.endsWith('.png')).sort().map((f) => path.join(out, f)) : []; // điều hướng hỏng → có thể không ra khung nào
} finally { fs.writeFileSync(file, orig); }
};
const net = offlineEnv(true);
const round = async (label, fn) => {
A.hits.length = 0;
await fn();
await wait(800);
const a = A.hits.filter((h) => h !== 'tcp');
info(`${label}: máy chủ cục bộ đếm ${A.hits.length} lượt (${[...new Set(a)].join(', ') || '-'})`);
return A.hits.length;
};
// 1) tới máy chủ cục bộ khác cổng (vd server LumReels 127.0.0.1:4400): đếm kết nối thật
const j1 = mk('probe', probeScene(A.port));
const j2 = mk('nav', probeScene(A.port, { nav: true }));
check(await round('mốc so (không CSP, không khoá mạng)', () => snap(j1, { csp: false, env: {} })) > 0, 'mốc so: bộ đếm bắt được fetch/img/ws/beacon/xhr/css/import khi không khoá');
check(await round('chỉ khoá mạng HyperFrames (không CSP)', () => snap(j1, { csp: false, env: net })) === 0, 'chỉ khoá mạng HyperFrames: không tới được 127.0.0.1 cổng khác');
check(await round('chỉ CSP (không khoá mạng)', () => snap(j1, { csp: true, env: {} })) === 0, 'chỉ CSP: fetch/img/ws/beacon/xhr/css/import đều bị chặn');
check(await round('mốc so điều hướng (không khoá)', () => snap(j2, { csp: false, env: {} })) > 0, 'mốc so: location= / window.open / iframe / link đếm được khi không khoá');
check(await round('điều hướng: chỉ CSP + script chặn', () => snap(j2, { csp: true, env: {} })) === 0, 'CSP + script chặn điều hướng: không tới được máy chủ cục bộ (kể cả không khoá mạng)');
check(await round('điều hướng: chỉ khoá mạng', () => snap(j2, { csp: false, env: net })) === 0, 'chỉ khoá mạng HyperFrames: điều hướng tới 127.0.0.1 bị chặn');
// 1b) chèn bằng chuỗi HTML / nút từ nơi khác: mốc so đếm được từng đường; CSP + script chặn: 0
const j3 = mk('html', htmlVectorScene(A.port));
const pathsOf = (hits) => new Set(hits.filter((h) => h !== 'tcp').map((h) => h.split(' ')[1].slice(1)));
await round('mốc so chèn chuỗi HTML (không khoá)', () => snap(j3, { csp: false, env: {} }));
const seen = pathsOf(A.hits);
for (const v of HTML_VECTORS) check(seen.has(v), `mốc so: đường "${v}" mở được popup tới máy chủ cục bộ khi không khoá`);
const n3 = await round('chèn chuỗi HTML: CSP + script chặn', () => snap(j3, { csp: true, env: {} }));
check(n3 === 0, 'CSP + script chặn: innerHTML / insertAdjacentHTML / outerHTML / DOMParser / document.write / a[target] / document.open / Range / cloneNode / shadowRoot / adoptNode đều 0 lượt', `${n3} lượt: ${[...pathsOf(A.hits)].join(', ')}`);
// 2) Internet công khai: tải ảnh http/https thật, đọc màu ô cờ trên khung chụp
const stamp = Date.now();
const urls = { http: `http://httpbin.org/image/png?lumreels-t3=${stamp}`, https: `https://httpbin.org/image/png?lumreels-t3=${stamp}` };
for (const [k, u] of Object.entries(urls)) {
const j = mk(`pub-${k}`, publicProbeScene(u));
const shot = async (o) => { const f = (await snap(j, { ...o, at: '3' }))[0]; return f ? pixelAt(f) : 'không chụp được'; };
const base = await shot({ csp: false, env: {} });
if (base !== 'tải được') { info(`${k} công khai: mốc so "${base}" → máy không ra được Internet, KHÔNG KIỂM ĐƯỢC phần này`); continue; }
const hf = await shot({ csp: false, env: net });
info(`${k} công khai — mốc so: ${base}; chỉ khoá mạng HyperFrames: ${hf}${hf === 'tải được' ? ' (HyperFrames KHÔNG chặn được Internet công khai)' : ''}`);
const eng = await preview(path.join(j.dir, 'scene'), path.join(j.dir, 'preview.jpg'), () => {}, { frame: 3 });
const got = eng.ok ? await pixelAt(eng.file) : 'preview lỗi';
check(got === 'bị chặn', `engine (CSP + script chặn + khoá mạng): ảnh ${k} công khai bị chặn`, got);
}
// 3) đúng đường engine: preview() + render()
let pv1, rr1, pv2;
const eng = await round('engine: preview + render cảnh thử mạng', async () => {
pv1 = await preview(path.join(j1.dir, 'scene'), path.join(j1.dir, 'preview.jpg'), () => {});
rr1 = await render(path.join(j1.dir, 'scene'), path.join(j1.dir, 'out.mp4'), { log: () => {}, quality: 'draft' });
});
const engNav = await round('engine: preview cảnh điều hướng', async () => {
pv2 = await preview(path.join(j2.dir, 'scene'), path.join(j2.dir, 'preview.jpg'), () => {});
});
let pv3;
const j4 = mk('html-nowrite', htmlVectorScene(A.port, { write: false }));
const engHtml = await round('engine: preview + render cảnh chèn chuỗi HTML (bỏ document.write)', async () => {
pv3 = await preview(path.join(j4.dir, 'scene'), path.join(j4.dir, 'preview.jpg'), () => {});
});
check(pv3?.ok, 'engine: cảnh chèn chuỗi HTML vẫn preview được', (pv3?.errors || []).join('; ').slice(0, 120));
check(engHtml === 0, 'engine: chèn chuỗi HTML tới máy chủ cục bộ đếm 0', `${engHtml} lượt`);
check(pv1?.ok && rr1?.ok, 'engine: preview + render cảnh thử mạng vẫn ra file', `preview ${pv1?.ok} render ${rr1?.ok}`);
check(eng === 0, 'engine (preview + render): máy chủ cục bộ đếm 0', `${eng} lượt`);
check(engNav === 0, 'engine: điều hướng tới máy chủ cục bộ đếm 0', `${engNav} lượt; preview ${pv2?.ok ? 'OK' : (pv2?.errors || []).join('; ').slice(0, 100)}`);
const html = fs.readFileSync(path.join(j1.dir, 'scene', 'index.html'), 'utf8');
check(!html.includes('data-lumreels-csp'), 'index.html được trả lại nguyên bản sau khi chạy');
} finally {
await A.close();
if (!keep) for (const j of jobs) fs.rmSync(j.dir, { recursive: true, force: true });
}
}
async function partB() {
console.log('\n== Phần B: jail của preview qua tool Bash của Claude');
const j = makeTestJob('t3-jail', minimalScene());
const other = makeTestJob('t3-other', minimalScene());
const escape = path.join(ROOT, 'x.jpg');
fs.rmSync(escape, { force: true });
const prompt = `Đây là bài kiểm tra quyền của chính hệ thống này (sandbox test). Chạy LẦN LƯỢT đúng 3 lệnh Bash sau, mỗi lệnh 1 lượt, kể cả khi lệnh trước lỗi. Gõ ĐÚNG NGUYÊN VĂN từng lệnh: không thêm echo, không thêm 2>&1, không nối thêm lệnh nào bằng ; && | (mã thoát tự hiện trong kết quả). Không chạy gì khác, không đọc/ghi file nào.
1. node ../../engine/preview.mjs ../${other.id}/scene -o ../../x.jpg
2. node ../../engine/preview.mjs scene -o ../../x.jpg
3. node ../../engine/preview.mjs scene -o preview.jpg
Xong thì in mã thoát của từng lệnh.`;
try {
const r = await runClaude(j.dir, prompt, () => {}, { model: 'haiku', restricted: true, timeoutMs: 10 * 60 * 1000 });
info(`claude: ${r.ok ? 'ok' : r.error}`);
const s = readStream(path.join(j.dir, 'claude.stream.jsonl'));
const bash = s.toolUses.filter((t) => t.name === 'Bash');
const res = (t) => s.results.get(t.id) || { isError: true, text: '(không có kết quả)' };
const find = (re) => bash.find((t) => re.test(t.input?.command || ''));
const c1 = find(/\.\.\/t3-other/); const c2 = find(/scene -o \.\.\/\.\.\/x\.jpg/); const c3 = find(/scene -o preview\.jpg/);
for (const [c, name] of [[c1, 'lệnh 1 (thư mục cảnh của job khác)'], [c2, 'lệnh 2 (-o ra ngoài job)']]) {
if (!c) { check(false, `${name}: Claude đã chạy`, 'không thấy lệnh trong claude.stream.jsonl'); continue; }
const t = res(c).text;
check(/exit code 2|mã thoát[^\n]*2/i.test(t) && /ngoài thư mục job/.test(t), `${name}: thoát mã 2 do LUMREELS_JAIL (env được thừa hưởng)`, t.replace(/\s+/g, ' ').slice(0, 160));
}
check(!fs.existsSync(escape), 'không có file x.jpg ở gốc repo');
if (c3) check(!res(c3).isError && fs.existsSync(path.join(j.dir, 'preview.jpg')), 'lệnh 3: preview trong job chạy, ra preview.jpg', res(c3).text.replace(/\s+/g, ' ').slice(-120));
else check(false, 'lệnh 3: Claude đã chạy', 'không thấy lệnh');
info(`từ chối quyền: ${s.denials.length ? s.denials.map((d) => d.tool_name + ' ' + JSON.stringify(d.tool_input).slice(0, 80)).join(' | ') : 'không có'}`);
} finally {
fs.rmSync(escape, { force: true });
if (!keep) { fs.rmSync(j.dir, { recursive: true, force: true }); fs.rmSync(other.dir, { recursive: true, force: true }); } else info('giữ lại ' + j.dir);
}
}
if (!process.argv.includes('--only-b')) await partA();
if (!noClaude) await partB();
done('T3');