Skip to content

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.

9.7 KB
Raw Blame
#!/usr/bin/env node
// Kiểm nhật ký (server/logs.mjs): lọc bí mật, câu lỗi dễ hiểu, đọc đuôi log, chặn path traversal + Origin lạ.
//   node server/test/logs-check.mjs            → chỉ phần không cần server
//   node server/test/logs-check.mjs 4400       → thêm phần HTTP trên server đang chạy (chỉ GET, không ghi gì)
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import { redact, explain, tailFile, jobLog, logText } from '../logs.mjs';

let fail = 0; let pass = 0;
const ok = (cond, name, extra = '') => { if (cond) { pass++; console.log('PASS', name); } else { fail++; console.log('FAIL', name, extra); } };

// ---- 1. lọc bí mật ----
const home = os.homedir();
const SECRETS = [
  ['sk-ant-api03-AbCdEf1234567890_xyzXYZ-0987', 'khoá Anthropic sk-ant-'],
  ['sk-proj-ABCDEFGHIJKLMNOP1234567890', 'khoá OpenAI sk-proj-'],
  ['ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'token GitHub'],
  ['xoxb-1234567890-abcdefghijkl', 'token Slack'],
  ['AIzaSyA1234567890abcdefghijklmnopqrstuv', 'khoá Google'],
  ['AKIAABCDEFGHIJKLMNOP', 'khoá AWS'],
  ['eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U', 'JWT'],
];
for (const [sec, name] of SECRETS) {
  const out = redact(`lỗi gọi API với ${sec} rồi`);
  ok(!out.includes(sec) && out.includes('[đã ẩn]'), `redact ${name}`, out);
}
const lines = {
  'ANTHROPIC_API_KEY=abc123secretvalue': 'abc123secretvalue',
  'export OPENAI_API_KEY="qwe-rty-123456"': 'qwe-rty-123456',
  'MOTAPIS_API_KEY: zzzz9999': 'zzzz9999',
  'GITHUB_TOKEN=gho_short123': 'gho_short123',
  'Authorization: Bearer abcdef0123456789abcdef': 'abcdef0123456789abcdef',
  'authorization: Basic dXNlcjpwYXNzd29yZA==': 'dXNlcjpwYXNzd29yZA==',
  '{"headers":{"x-api-key":"k-1234567890"}}': 'k-1234567890',
  '{"api_key": "hunter2hunter2"}': 'hunter2hunter2',
  'password=Tr0ub4dor&3': 'Tr0ub4dor',
  'GET https://api.example.com/v1?key=SECRETKEY123&x=1': 'SECRETKEY123',
  'https://user:[email protected]/repo.git': 'pa55word',
  'Cookie: session=abcdef123456': 'session=abcdef123456',
};
for (const [line, secret] of Object.entries(lines)) {
  const out = redact(line);
  ok(!out.includes(secret), `redact "${line.slice(0, 32)}…"`, out);
}
// không phá chữ thường: số token, đường dẫn trong job, tiếng Việt
ok(redact('in 12.3k / out 4.5k tokens, outputTokens: 4500').includes('4500'), 'redact giữ số token (không phải bí mật)');
ok(redact('trạng thái → error: HyperFrames render lỗi (mã 1)') === 'trạng thái → error: HyperFrames render lỗi (mã 1)', 'redact giữ nguyên câu tiếng Việt');
// đường dẫn nhà → ~
for (const p of [path.join(home, 'Videos', 'a.mp4'), home.replace(/\\/g, '/') + '/x/y.json', home.replace(/\\/g, '\\\\') + '\\\\z']) {
  const out = redact(`file ${p} lỗi`);
  ok(!out.toLowerCase().includes(home.toLowerCase()) && !out.toLowerCase().includes(home.replace(/\\/g, '/').toLowerCase()) && out.includes('~'), `redact đường dẫn nhà (${p.slice(-12)})`, out);
}

// ---- 2. câu lỗi dễ hiểu ----
const WHY = {
  'API 401 AuthenticationError: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}': 'api_key',
  'Invalid API key · Please run /login': 'claude_login',
  'API 429 {"type":"error","error":{"type":"rate_limit_error"}}': 'quota',
  'Your credit balance is too low to access the Anthropic API': 'quota',
  'spawn ffmpeg ENOENT': 'ffmpeg',
  "No module named 'faster_whisper'": 'python',
  'ENOSPC: no space left on device, write': 'disk',
  'ổ đĩa còn 1.2 GB, cần ≥ 5.0 GB': 'disk',
  'Claude Code quá giờ (25 phút)': 'timeout',
  'phân tích lỗi: Library cublas64_12.dll is not found or cannot be loaded': 'cuda',
  'server khởi động lại khi job đang chạy': 'interrupted',
  'Overloaded (529)': 'overloaded',
  'không nghe được lời nào trong video': 'no_speech',
};
for (const [msg, code] of Object.entries(WHY)) ok(explain(msg) === code, `explain → ${code}`, `${explain(msg)} ← ${msg}`);
ok(explain('một lỗi lạ chưa ai gặp xyz') === null, 'explain lỗi lạ → null (UI hiện nguyên văn)');
ok(explain('HyperFrames render lỗi (mã 1)', ['render 40% capture 401/600']) === 'scene_invalid', 'explain không nhầm 401/600 khung là lỗi 401');

// ---- 3. đọc đuôi + nhật ký job (thư mục tạm, không đụng jobs/ thật) ----
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'logs-check-'));
try {
  const jd = path.join(tmp, 'jobs'); const ed = path.join(tmp, 'edits');
  fs.mkdirSync(path.join(jd, 'j1'), { recursive: true }); fs.mkdirSync(path.join(ed, 'e1'), { recursive: true });
  const many = Array.from({ length: 500 }, (_, i) => `[10:00:${String(i % 60).padStart(2, '0')}] dòng ${i}`);
  many.push('[10:01:00] trạng thái → generating', `[10:01:01] gọi API với ANTHROPIC_API_KEY=sk-ant-api03-secretsecretsecret123`, `[10:01:02] đọc ${path.join(home, 'secret.txt')}`, '[10:01:03] trạng thái → error: API 401 AuthenticationError');
  fs.writeFileSync(path.join(jd, 'j1', 'log.txt'), many.join('\n') + '\n');
  const tf = tailFile(path.join(jd, 'j1', 'log.txt'));
  ok(tf.lines.length === 300 && tf.truncated && tf.total === 504, 'tailFile 300 dòng cuối', JSON.stringify({ n: tf.lines.length, t: tf.total }));
  const ctx = { jobsDir: jd, editsDir: ed, readJob: (id) => (id === 'j1' ? { id, status: 'error', error: 'API 401 AuthenticationError sk-ant-api03-secretsecretsecret123', templateId: '009' } : null),
    readEdit: (id) => (id === 'e1' ? { id, status: 'error', step: 'phân tích', error: 'phân tích lỗi: CUDA failed', sourceName: 'clip.mp4' } : null) };
  const v = jobLog('job', 'j1', ctx);
  const all = JSON.stringify(v);
  ok(v && v.failed && v.step === 'generating' && v.why === 'api_key', 'jobLog: bước hỏng + mã lỗi', JSON.stringify({ step: v?.step, why: v?.why }));
  ok(!all.includes('secretsecret') && !all.toLowerCase().includes(home.toLowerCase().replace(/\\/g, '\\\\')), 'jobLog không lộ khoá / đường dẫn nhà');
  ok(!logText(v).includes('secretsecret'), 'file .txt không lộ khoá');
  const e = jobLog('edit', 'e1', ctx);
  ok(e && e.step === 'phân tích' && e.why === 'cuda', 'jobLog edit: bước + mã lỗi CUDA', JSON.stringify({ step: e?.step, why: e?.why }));
  for (const bad of ['..', '../jobs', '..\\j1', 'j1/../j1', '', 'a'.repeat(81), 'j1.', '%2e%2e']) ok(jobLog('job', bad, ctx) === null, `jobLog chặn id "${bad.slice(0, 12)}"`);
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }

// ---- 4. HTTP trên server đang chạy (chỉ GET) ----
const port = Number(process.argv[2]);
function get(p, headers = {}, method = 'GET') {
  return new Promise((resolve) => {
    const req = http.request({ host: '127.0.0.1', port, path: p, method, headers: { Host: `127.0.0.1:${port}`, ...headers } }, (res) => {
      let b = ''; res.setEncoding('utf8'); res.on('data', (c) => { b += c; }); res.on('end', () => resolve({ code: res.statusCode, headers: res.headers, body: b }));
    });
    req.on('error', (e) => resolve({ code: 0, body: e.message }));
    req.end();
  });
}
if (port) {
  const s = await get('/api/logs/server');
  ok(s.code === 200 && Array.isArray(JSON.parse(s.body).lines), 'GET /api/logs/server 200');
  ok(!/sk-ant-[A-Za-z0-9]{10}/.test(s.body) && !s.body.toLowerCase().includes(home.toLowerCase().replace(/\\/g, '\\\\')), 'log server không lộ khoá / đường dẫn nhà');
  for (const p of ['/api/logs/job/..', '/api/logs/job/..%2F..%2Fpackage.json', '/api/logs/job/%2e%2e', '/api/logs/edit/..%5C..%5Cserver', '/api/logs/job/a%2Fb', '/api/logs/job/' + 'x'.repeat(81), '/api/logs/job/x.y', '/api/logs/foo/abc', '/api/logs/job/../../package.json']) {
    const r = await get(p);
    ok([400, 404].includes(r.code) && !r.body.includes('"version"') && !r.body.includes('"lines"'), `chặn ${p.slice(0, 44)} → ${r.code}`);
  }
  const nf = await get('/api/logs/job/khong-co-job-nay');
  ok(nf.code === 404, 'job không có → 404');
  const evil = await get('/api/logs/server', { Origin: 'http://evil.example' });
  ok(evil.code === 403, 'Origin lạ → 403', String(evil.code));
  const own = await get('/api/logs/server', { Origin: `http://127.0.0.1:${port}` });
  ok(own.code === 200, 'Origin của app → 200');
  const post = await get('/api/logs/server', {}, 'POST');
  ok(post.code === 403 || post.code === 405, 'POST → bị từ chối (chỉ đọc)', String(post.code));
  const del = await get('/api/logs/job/abc', {}, 'DELETE');
  ok([403, 405].includes(del.code), 'DELETE → bị từ chối', String(del.code));
  const rebind = await get('/api/logs/server', { Host: 'evil.example' });
  ok(rebind.code === 421, 'Host lạ (DNS rebinding) → 421');
  // 1 job lỗi có thật (nếu có): mã lỗi + tải .txt
  const jobs = JSON.parse((await get('/api/jobs')).body);
  const bad = jobs.find((j) => j.status === 'error');
  if (bad) {
    const r = await get('/api/logs/job/' + bad.id);
    const v = JSON.parse(r.body);
    ok(r.code === 200 && v.failed && v.lines.length > 0, `nhật ký job lỗi ${bad.id}: ${v.why || 'không mã'} · bước ${v.step}`);
    const d = await get('/api/logs/job/' + bad.id + '?download=1');
    ok(d.code === 200 && /attachment; filename="lumreels-job-[\w-]+-log\.txt"/.test(d.headers['content-disposition'] || '') && /^text\/plain/.test(d.headers['content-type']), 'tải .txt có Content-Disposition');
  } else console.log('(không có job lỗi để thử tải .txt)');
  const eds = JSON.parse((await get('/api/edits')).body);
  if (eds[0]) { const r = await get('/api/logs/edit/' + eds[0].id); ok(r.code === 200 && Array.isArray(JSON.parse(r.body).lines), 'nhật ký edit 200'); }
}

console.log(`\n${pass} PASS, ${fail} FAIL`);
process.exit(fail ? 1 : 0);