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.

14.6 KB
Raw Blame
// REST cho gói mẫu .lumpack (server/server.mjs gọi handlePackRoute). THIET-KE gói mẫu §5.1, luật L9, L10, L12, L13.
// Host đã chặn ở server (chống DNS rebinding); ở đây chặn thêm Origin lạ cho mọi lệnh ghi (403).
//   GET    /api/packs                              → gói đã cài: id, tên, phiên bản, tác giả, giấy phép, số mục, nguồn, verified, mục
//   GET    /api/packs/:id                          → 1 gói + nguyên văn từng mục (để người dùng xem lại)
//   POST   /api/packs/inspect                      → multipart `file` ≤ 12 MB: báo cáo kiểm + mục + nguyên văn .md + fileSha256.
//                                                    Không ghi gì vào packs/; bản đã xem giữ trong RAM 10 phút
//   POST   /api/packs/install                      → {fileSha256, replace?}: cài đúng bản vừa xem (1 lúc 1 lượt)
//   DELETE /api/packs/:id                          → gỡ gói (local.* không gỡ cả gói được)
//   DELETE /api/packs/:id/items/:kind/:slug        → xoá 1 mục tự tạo (local.*)
//   POST   /api/packs/export                       → {id, version, name, author, license, items:[ref]} → file .lumpack
//   GET    /pack-thumbs/<packId>/<kind>-<slug>.webp   ảnh đại diện mục đã cài
//   GET    /pack-preview/<fileSha256>/<kind>-<slug>.webp  ảnh của gói đang xem trước (chưa cài)
// Không có đường nào tải gói từ mạng (thư viện là P5) và MCP không có tool cài: cài phải do người bấm.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { readPack, installPack, uninstallPack, removeItem, exportPack, cmpVersion, MAX_FILE_BYTES, LICENSES } from './pack.mjs';
import { listPacks, readPackManifest, validPackId, validSlug, KINDS, RESERVED_AUTHORS, itemFile, thumbFile, packDir } from './registry.mjs';
import { WARN_WORDS, parseFrontmatter, splitStyle } from './lint.mjs';
import { parseMultipart, originOk, sendAndClose } from '../edit/http.mjs';

const httpErr = (code, msg, extra = {}) => Object.assign(new Error(msg), { code, ...extra });
const STAGE_MS = 10 * 60 * 1000;
const STAGE_MAX = 6;
const SHA_RE = /^[0-9a-f]{64}$/;
/** Bản đã xem trước, chờ bấm Cài: fileSha256 → {pack, at}. */
const staged = new Map();
let inspecting = false;

function prune() {
  const now = Date.now();
  for (const [k, v] of staged) if (now - v.at > STAGE_MS) staged.delete(k);
  while (staged.size > STAGE_MAX) staged.delete(staged.keys().next().value);
}

/** Lỗi đọc gói → mã cho UI tự chọn chữ VI/EN: not-pack | engine | rejected. */
function errorCode(errors) {
  if (!errors.length) return null;
  if (errors.some((e) => /cần LumReels ≥/.test(e))) return 'engine';
  if (errors.some((e) => /không phải (file )?gói|không đọc được file gói|^file gói >|không phải file$/.test(e))) return 'not-pack';
  return 'rejected';
}
/** So với gói đã cài cùng id: new | installed | conflict | older | upgrade. */
function installState(manifest) {
  if (!manifest || !validPackId(manifest.id)) return { state: 'new', installedVersion: null };
  const cur = readPackManifest(manifest.id);
  if (!cur) return { state: 'new', installedVersion: null };
  let c = 0;
  try { c = cmpVersion(manifest.version, cur.version); } catch { return { state: 'conflict', installedVersion: cur.version }; }
  if (c === 0) return { state: cur.contentHash === manifest.contentHash ? 'installed' : 'conflict', installedVersion: cur.version };
  return { state: c < 0 ? 'older' : 'upgrade', installedVersion: cur.version };
}
const itemName = (it) => {
  if (it.kind === 'template') return it.frontmatter?.title || it.slug;
  return it.preset?.name || it.slug;
};
/** Chỉ dữ liệu, không HTML: UI đưa mọi trường vào textContent (L9). */
function inspectView(pack) {
  const m = pack.manifest || {};
  const errors = pack.report.errors;
  const st = installState(pack.manifest);
  return {
    fileSha256: pack.fileSha256,
    ok: !errors.length,
    code: errorCode(errors),
    errors, warnings: pack.report.warnings, warnWords: WARN_WORDS,
    install: st,
    canInstall: !errors.length && (st.state === 'new' || st.state === 'upgrade'),
    pack: pack.manifest ? {
      id: m.id, version: m.version, name: m.name, nameEn: m.nameEn || null, description: m.description || '',
      author: m.author && typeof m.author === 'object' ? { name: m.author.name, contact: m.author.contact || null } : null,
      license: m.license, provenance: m.provenance, createdAt: m.createdAt || null, engineMin: m.engine?.min || null,
      community: true, restricted: true,
    } : null,
    items: pack.items.map((it) => ({
      kind: it.kind, slug: it.slug, name: itemName(it), blurb: it.blurb || '', warnings: it.warnings,
      text: it.text, thumb: it.thumbBuf && pack.fileSha256 ? `/pack-preview/${pack.fileSha256}/${it.kind}-${it.slug}.webp` : null,
      ...(it.frontmatter ? { category: it.frontmatter.category || null, technique: it.frontmatter.technique || [] } : {}),
    })),
  };
}

function sourceLabel(packId) { return packId.startsWith('local.') ? 'local' : 'pack'; }
function packSummary(m) {
  return {
    id: m.id, version: m.version, name: m.name, nameEn: m.nameEn || null, description: m.description || '',
    author: m.author ? { name: m.author.name, contact: m.author.contact || null } : null, license: m.license, provenance: m.provenance || null,
    source: sourceLabel(m.id), installSource: m.source || null, verified: !!m.verified, installedAt: m.installedAt || null,
    itemCount: (m.items || []).length,
    items: (m.items || []).map((x) => {
      let name = x.slug;
      try {
        const md = fs.readFileSync(itemFile(m.id, x.kind, x.slug), 'utf8');
        if (x.kind === 'template') name = parseFrontmatter(md.replace(/\r\n/g, '\n'))?.fm?.title || x.slug;
        else { const sp = splitStyle(md.replace(/\r\n/g, '\n')); name = sp ? (JSON.parse(sp.json).name || x.slug) : x.slug; }
      } catch { /* file mất: giữ slug */ }
      return { kind: x.kind, slug: x.slug, ref: `${m.id}/${x.slug}`, name, thumb: thumbFile(m.id, x.kind, x.slug) ? `/pack-thumbs/${m.id}/${x.kind}-${x.slug}.webp` : null };
    }),
  };
}

/** Thân JSON nhỏ, bắt buộc Content-Type JSON (form HTML không gửi được kiểu này mà không qua CORS preflight). */
async function jsonBody(req, readBody, limit = 32 * 1024) {
  if (!/^application\/json\b/i.test(String(req.headers['content-type'] || ''))) throw httpErr(415, 'cần Content-Type: application/json');
  return readBody(req, limit);
}

/** Trả true nếu đã xử lý route. */
export async function handlePackRoute(req, res, p, { send, readBody, serveFile, allowedHosts }) {
  const isGet = req.method === 'GET' || req.method === 'HEAD';
  // ---- ảnh (L10: chỉ webp đã kiểm lúc cài; serveFile gửi image/webp + nosniff) ----
  let m = /^\/pack-thumbs\/([a-z0-9.-]{5,49})\/(template|edit-style)-([a-z][a-z0-9-]{1,31})\.webp$/.exec(p);
  if (m && isGet) {
    const f = validPackId(m[1]) && validSlug(m[3]) ? thumbFile(m[1], m[2], m[3]) : null;
    if (!f) { send(res, 404, { error: 'không thấy ảnh' }); return true; }
    serveFile(req, res, path.dirname(f), path.basename(f));
    return true;
  }
  m = /^\/pack-preview\/([0-9a-f]{64})\/(template|edit-style)-([a-z][a-z0-9-]{1,31})\.webp$/.exec(p);
  if (m && isGet) {
    prune();
    const it = staged.get(m[1])?.pack.items.find((x) => x.kind === m[2] && x.slug === m[3]);
    if (!it?.thumbBuf) { send(res, 404, { error: 'không thấy ảnh' }); return true; }
    res.writeHead(200, { 'Content-Type': 'image/webp', 'Content-Length': it.thumbBuf.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
    res.end(req.method === 'HEAD' ? undefined : it.thumbBuf);
    return true;
  }
  if (!p.startsWith('/api/packs')) return false;
  if (!isGet && !originOk(req, allowedHosts)) { sendAndClose(res, req, send, 403, { error: 'origin không hợp lệ' }); return true; }

  try {
    if (p === '/api/packs' && isGet) { send(res, 200, { packs: listPacks().map(packSummary), licenses: LICENSES, reservedAuthors: RESERVED_AUTHORS }); return true; }

    if (p === '/api/packs/inspect' && req.method === 'POST') {
      if (!/^multipart\/form-data/i.test(String(req.headers['content-type'] || ''))) { sendAndClose(res, req, send, 415, { error: 'cần multipart/form-data (trường file)' }); return true; }
      const len = Number(req.headers['content-length']);
      if (!Number.isFinite(len) || len <= 0) { sendAndClose(res, req, send, 411, { error: 'cần Content-Length' }); return true; }
      if (len > MAX_FILE_BYTES + 64 * 1024) { sendAndClose(res, req, send, 413, { error: `file gói > ${MAX_FILE_BYTES / 1024 / 1024} MB`, code: 'not-pack' }); return true; }
      if (inspecting) { sendAndClose(res, req, send, 429, { error: 'đang đọc 1 gói khác, chờ chút rồi thử lại' }); return true; }
      inspecting = true;
      const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lumreels-inspect-'));
      try {
        const { files } = await parseMultipart(req, {
          maxBytes: MAX_FILE_BYTES + 64 * 1024, tooBig: `file gói > ${MAX_FILE_BYTES / 1024 / 1024} MB`,
          fileTarget: (field) => (field === 'file' ? path.join(tmpDir, 'pack.lumpack') : null),
        });
        if (!files.file?.size) throw httpErr(400, 'thiếu file gói (trường file)');
        const pack = readPack(files.file.path, { source: 'file' });
        if (pack.fileSha256) { staged.set(pack.fileSha256, { pack, at: Date.now() }); prune(); }
        send(res, 200, inspectView(pack));
      } catch (e) {
        const code = Number.isInteger(e.code) ? e.code : 400;
        if (!res.headersSent) { if (req.complete) send(res, code, { error: e.message }); else sendAndClose(res, req, send, code, { error: e.message }); }
      } finally {
        inspecting = false;
        fs.rmSync(tmpDir, { recursive: true, force: true });
      }
      return true;
    }

    if (p === '/api/packs/install' && req.method === 'POST') {
      const body = await jsonBody(req, readBody);
      const sha = String(body.fileSha256 || '');
      if (!SHA_RE.test(sha)) throw httpErr(400, 'thiếu fileSha256 của bản đã xem trước');
      prune();
      const st = staged.get(sha);
      if (!st) throw httpErr(410, 'bản xem trước đã hết hạn (10 phút): chọn lại file gói', { errCode: 'expired' });
      const view = inspectView(st.pack);
      if (!view.ok) throw httpErr(422, 'gói bị từ chối: ' + view.errors[0], { errCode: view.code });
      if (view.install.state === 'installed') throw httpErr(409, `gói ${view.pack.id} ${view.install.installedVersion} đã cài rồi`, { errCode: 'installed' });
      if (view.install.state === 'conflict') throw httpErr(409, `đã cài ${view.pack.id} ${view.install.installedVersion}, bản này cùng phiên bản mà nội dung khác`, { errCode: 'conflict' });
      if (view.install.state === 'older') throw httpErr(409, `đã cài ${view.pack.id} ${view.install.installedVersion}, mới hơn bản này`, { errCode: 'older' });
      if (view.install.state === 'upgrade' && body.replace !== true) throw httpErr(409, `đã cài ${view.pack.id} ${view.install.installedVersion}; cài ${view.pack.version} cần xác nhận thay`, { errCode: 'upgrade' });
      let man;
      try { man = installPack(st.pack, { source: 'file', replace: body.replace === true }); } catch (e) { throw httpErr(/đang cài/.test(e.message) ? 429 : 409, e.message); }
      staged.delete(sha);
      console.log(`[packs] cài ${man.id} ${man.version} (${man.items.length} mục)`);
      send(res, 201, packSummary(man));
      return true;
    }

    if (p === '/api/packs/export' && req.method === 'POST') {
      const body = await jsonBody(req, readBody);
      if (!validPackId(body.id)) throw httpErr(400, 'id gói phải dạng tac-gia.ten-goi (chữ thường không dấu, số, gạch nối)');
      if (RESERVED_AUTHORS.includes(String(body.id).split('.')[0])) throw httpErr(400, `tác giả "${String(body.id).split('.')[0]}" dành riêng, chọn tên khác`, { errCode: 'reserved' });
      if (!Array.isArray(body.items) || !body.items.length || body.items.length > 200) throw httpErr(400, 'chọn 1–200 mục để xuất');
      const authorName = typeof body.author === 'string' ? body.author : body.author?.name;
      const r = exportPack({
        id: body.id, version: body.version || '1.0.0', name: body.name, author: { name: authorName, ...(body.contact ? { contact: String(body.contact) } : {}) },
        license: body.license || 'CC-BY-4.0', provenance: 'own-video' === body.provenance ? 'own-video' : 'original', items: body.items.map(String),
        description: body.description || undefined,
      });
      res.writeHead(200, {
        'Content-Type': 'application/octet-stream', 'Content-Length': r.buffer.length, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
        'Content-Disposition': `attachment; filename="${r.manifest.id}-${r.manifest.version}.lumpack"`, 'X-Lumpack-Sha256': r.fileSha256,
      });
      res.end(r.buffer);
      return true;
    }

    m = /^\/api\/packs\/([a-z0-9.-]{5,49})$/.exec(p);
    if (m && isGet) {
      const man = validPackId(m[1]) ? readPackManifest(m[1]) : null;
      if (!man) throw httpErr(404, 'chưa cài gói này');
      const v = packSummary(man);
      v.items = v.items.map((x) => { let text = ''; try { text = fs.readFileSync(itemFile(man.id, x.kind, x.slug), 'utf8'); } catch { /* mất file */ } return { ...x, text }; });
      send(res, 200, { ...v, warnWords: WARN_WORDS });
      return true;
    }
    if (m && req.method === 'DELETE') {
      if (!validPackId(m[1])) throw httpErr(400, 'id gói không hợp lệ');
      if (!readPackManifest(m[1])) throw httpErr(404, 'chưa cài gói này');
      try { uninstallPack(m[1]); } catch (e) { throw httpErr(400, e.message); }
      console.log(`[packs] gỡ ${m[1]}`);
      send(res, 200, { ok: true, id: m[1] });
      return true;
    }
    m = /^\/api\/packs\/([a-z0-9.-]{5,49})\/items\/(template|edit-style)\/([a-z][a-z0-9-]{1,31})$/.exec(p);
    if (m && req.method === 'DELETE') {
      if (!validPackId(m[1]) || !validSlug(m[3]) || !KINDS[m[2]]) throw httpErr(400, 'mục không hợp lệ');
      packDir(m[1]);
      let r;
      try { r = removeItem(m[1], m[2], m[3]); } catch (e) { throw httpErr(/không thấy/.test(e.message) ? 404 : 400, e.message); }
      send(res, 200, { ok: true, ...r });
      return true;
    }
    send(res, 404, { error: 'không có API này' });
    return true;
  } catch (e) {
    const code = Number.isInteger(e.code) ? e.code : 400;
    if (!res.headersSent) send(res, code, { error: e.message, ...(e.errCode ? { code: e.errCode } : {}) });
    return true;
  }
}