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.
Sửa theo QA bộ cài + Kiểm tra máy: C1, V1–V7 và một số lỗi Thấp
Lumtek096625b2cc8b
diff --git a/README.md b/README.mdindex 22acdd9..86d4960 100644--- a/README.md+++ b/README.md@@ -58,10 +58,14 @@ powershell -ExecutionPolicy Bypass -c "irm https://raw.githubusercontent.com/lum```- No admin rights needed when a package has a per-user build (`winget --scope user`); Node and Chrome may ask for admin once.-- Safe to re-run: an existing install only does `git pull` + `npm install`. Check only, install nothing: `LumReels-Setup.cmd -DryRun`.+- The installer takes the **latest release tag** (`v*`); with no tag yet it uses `main` and prints a warning. Pin another version with `-Ref v0.2.0` (tag, commit or branch).+- Safe to re-run: an existing install only moves to that `-Ref` and runs `npm install`. Check only, install nothing: `LumReels-Setup.cmd -DryRun`.- Log: `%LOCALAPPDATA%\LumReels\install.log`. No `winget` on the machine: install **App Installer** from the Microsoft Store and run it again.- Uninstall: `powershell -ExecutionPolicy Bypass -File "%LOCALAPPDATA%\LumReels\app\install\windows\uninstall.ps1"`. Rendered videos move to `~/.lumreels/backup-…`; keys and voices in `~/.lumreels` stay unless you add `-Purge`.+**For maintainers:** the installer only sees a new version once a `v*` tag exists on GitHub. To release: bump `version` in `package.json`, commit to `main`, then+`git tag -a v0.2.0 -m "LumReels 0.2.0" && git push origin v0.2.0`. Use `vX.Y.Z` (the installer sorts by version, so `v0.10.0` beats `v0.9.0`).+### Manual install (macOS, Linux, or by hand on Windows)You need **Node 22+**, **ffmpeg** and **Google Chrome**.diff --git a/README.vi.md b/README.vi.mdindex 1d983d3..de6bc2d 100644--- a/README.vi.md+++ b/README.vi.md@@ -58,10 +58,14 @@ powershell -ExecutionPolicy Bypass -c "irm https://raw.githubusercontent.com/lum```- Không cần quyền admin khi gói có bản cho riêng người dùng (`winget --scope user`); Node và Chrome có thể hỏi quyền admin một lần.-- Chạy lại an toàn: bản đã cài thì chỉ `git pull` + `npm install`. Chỉ kiểm, không cài gì: `LumReels-Setup.cmd -DryRun`.+- Bộ cài lấy **tag phát hành mới nhất** (`v*`); repo chưa có tag thì dùng `main` và in cảnh báo. Ghim bản khác: `-Ref v0.2.0` (tag, commit hoặc nhánh).+- Chạy lại an toàn: bản đã cài thì chỉ cập nhật về đúng `-Ref` + `npm install`. Chỉ kiểm, không cài gì: `LumReels-Setup.cmd -DryRun`.- Log: `%LOCALAPPDATA%\LumReels\install.log`. Máy chưa có `winget`: cài **App Installer** từ Microsoft Store rồi chạy lại.- Gỡ: `powershell -ExecutionPolicy Bypass -File "%LOCALAPPDATA%\LumReels\app\install\windows\uninstall.ps1"`. Video đã dựng được chuyển sang `~/.lumreels/backup-…`; khoá và giọng trong `~/.lumreels` giữ nguyên, thêm `-Purge` để xoá cả.+**Cho người phát hành (dev):** bộ cài chỉ thấy bản mới khi có tag `v*` trên GitHub. Phát hành: cập nhật `version` trong `package.json`, commit lên `main`, rồi+`git tag -a v0.2.0 -m "LumReels 0.2.0" && git push origin v0.2.0`. Tag theo dạng `vX.Y.Z` (bộ cài sắp theo số phiên bản, `v0.10.0` mới hơn `v0.9.0`).+### Cài thủ công (macOS, Linux, hoặc tự làm trên Windows)Cần **Node 22+**, **ffmpeg** và **Google Chrome**.diff --git a/generator/api.mjs b/generator/api.mjsindex ceb368d..347b4c6 100644--- a/generator/api.mjs+++ b/generator/api.mjs@@ -54,7 +54,8 @@ export function authMessage(status, { claudeAvailable = false } = {}) {export async function runApi(job, dir, prompt, log, saveUsage = () => {}) {if (!config.hasApiKey()) return { ok: false, error: 'Chưa có khoá Anthropic. Mở "Kiểm tra máy" để dán khoá, hoặc chọn Ai dựng cảnh: Claude Code.' };- const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 2 });+ const apiKey = process.env.ANTHROPIC_API_KEY; // giữ khoá của lượt này (đổi khoá giữa job không đánh dấu nhầm khoá mới)+ const client = new Anthropic({ apiKey, maxRetries: 2 });const usage = { calls: [], inputTokens: 0, outputTokens: 0, costUSD: 0 };const record = (model, purpose, u) => {const c = costOf(model, u);@@ -148,7 +149,7 @@ So ẢNH 1 với ẢNH 2 và guidance. Trả lời từng câu §12 "Tự kiểmreturn { ok: true, usage };} catch (e) {if (e instanceof Anthropic.APIError && (e.status === 401 || e.status === 403)) {- markKeyRejected(process.env.ANTHROPIC_API_KEY, e.status);+ markKeyRejected(apiKey, e.status);return { ok: false, authError: true, status: e.status, error: authMessage(e.status), usage };}const msg = e instanceof Anthropic.APIError ? `API ${e.status ?? ''} ${e.name}: ${String(e.message).slice(0, 300)}` : e.message;diff --git a/generator/jobs.mjs b/generator/jobs.mjsindex eb85bcf..c1e15cc 100644--- a/generator/jobs.mjs+++ b/generator/jobs.mjs@@ -8,6 +8,7 @@ import { config, resolveModel } from './config.mjs';import { buildPrompt } from './prompt.mjs';import { runClaude, findClaude } from './claude.mjs';import { runApi, authMessage } from './api.mjs';+import { cachedCheck } from './user-key.mjs';import { preview } from '../engine/preview.mjs';import { render } from '../engine/render.mjs';import { lintScene, syncLib } from '../engine/lib.mjs';@@ -222,7 +223,8 @@ export function jobRestricted(job) {/** auto → api (có ANTHROPIC_API_KEY) → claude (có lệnh claude) → manual. */export function resolveMode(mode) {if (mode !== 'auto') return mode;- if (config.hasApiKey()) return 'api';+ // khoá đã biết là sai (401/403 gần đây) mà máy có Claude Code → đi thẳng Claude Code, khỏi gọi API ăn 401 trước+ if (config.hasApiKey() && !(cachedCheck(process.env.ANTHROPIC_API_KEY)?.valid === false && findClaude())) return 'api';if (findClaude()) return 'claude';return 'manual';}diff --git a/generator/rewrite.mjs b/generator/rewrite.mjsindex 77aaaac..5cdccea 100644--- a/generator/rewrite.mjs+++ b/generator/rewrite.mjs@@ -8,6 +8,7 @@ import path from 'node:path';import { spawn } from 'node:child_process';import Anthropic from '@anthropic-ai/sdk';import { config, costOf } from './config.mjs';+import { markKeyRejected } from './user-key.mjs';import { findClaude, spawnClaude } from './claude.mjs';import crypto from 'node:crypto';import { parseDuration, fmtDuration } from './jobs.mjs';@@ -96,8 +97,15 @@ const NO_AI = 'Chưa cấu hình AI: mở "Kiểm tra máy" để dán khoá Antasync function viaApi(prompt) {const model = process.env.REWRITE_MODEL || 'claude-haiku-5-5';- const client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, maxRetries: 1, timeout: REWRITE_TIMEOUT_MS });- const msg = await client.messages.create({ model, max_tokens: 4000, messages: [{ role: 'user', content: prompt }] });+ const apiKey = process.env.ANTHROPIC_API_KEY;+ const client = new Anthropic({ apiKey, maxRetries: 1, timeout: REWRITE_TIMEOUT_MS });+ let msg;+ try {+ msg = await client.messages.create({ model, max_tokens: 4000, messages: [{ role: 'user', content: prompt }] });+ } catch (e) {+ if (e instanceof Anthropic.APIError && (e.status === 401 || e.status === 403)) markKeyRejected(apiKey, e.status); // Kiểm tra máy báo đúng ngay+ throw e;+ }if (msg.stop_reason === 'refusal') throw new Error(`${model} từ chối viết lại`);const text = (msg.content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\n');const u = msg.usage || {};diff --git a/generator/user-key.mjs b/generator/user-key.mjsindex 6c3902f..47c7551 100644--- a/generator/user-key.mjs+++ b/generator/user-key.mjs@@ -33,6 +33,19 @@ function restrict(file) {return r.status === 0;}+/** File khoá có đang chỉ người dùng đọc được không: true | false | null (không có file / không kiểm được). */+export function credFileRestricted() {+ const file = credFile();+ if (!fs.existsSync(file)) return null;+ if (process.platform !== 'win32') { try { return (fs.statSync(file).mode & 0o077) === 0; } catch { return null; } }+ const r = spawnSync('icacls', [file], { windowsHide: true, encoding: 'utf8', timeout: 10000 });+ if (r.status !== 0) return null;+ const out = String(r.stdout || '');+ // còn quyền kế thừa (I) hoặc cấp cho nhóm rộng → chưa siết+ if (/\(I\)/.test(out) || /Everyone|\\Users:|Authenticated Users|BUILTIN\\/i.test(out) || /\*S-1-1-0|\*S-1-5-11|\*S-1-5-32-545/.test(out)) return false;+ return true;+}+/** Khoá đã lưu trong app, hoặc null. */export function readUserKey() {const k = readCred().anthropicApiKey;diff --git a/install/windows/install.ps1 b/install/windows/install.ps1index d787ddb..184201f 100644--- a/install/windows/install.ps1+++ b/install/windows/install.ps1@@ -4,7 +4,9 @@# powershell -ExecutionPolicy Bypass -c "irm https://raw.githubusercontent.com/lumtekvn/lumreels/main/install/windows/install.ps1 | iex"# Làm gì: kiểm rồi cài thiếu (qua winget) Node 22+, ffmpeg, Google Chrome, Git → clone/cập nhật mã vào# %LOCALAPPDATA%\LumReels\app → npm install → shortcut "LumReels" ở Desktop + Start Menu → mở app.-# Chạy lại an toàn: thứ đã có thì bỏ qua, mã đã clone thì git pull.+# Chạy lại an toàn: thứ đã có thì bỏ qua, mã đã clone thì chỉ cập nhật.+# -Ref: tag/commit/nhánh cần cài. Mặc định: tag phát hành mới nhất (v*) trên GitHub; repo chưa có tag nào thì+# dùng nhánh mặc định (main) và in cảnh báo. Ghim tag thì app không tự báo bản mới (cài lại để lên tag mới).# -DryRun: chỉ kiểm và in việc sẽ làm, không cài, không tải, không tạo gì (trừ file log).# Log: %LOCALAPPDATA%\LumReels\install.log# File này phải lưu UTF-8 có BOM (Windows PowerShell 5.1 mới đọc đúng chữ có dấu).@@ -14,9 +16,12 @@ param([switch]$NoShortcut,[string]$InstallDir = (Join-Path $env:LOCALAPPDATA 'LumReels\app'),[string]$Repo = 'https://github.com/lumtekvn/lumreels.git',- [string]$Branch = ''+ [string]$Ref = '')+# chạy qua `irm | iex` thì các biến này nằm trong phiên của người dùng: nhớ để trả lại ở cuối+$savedEAP = $ErrorActionPreference; $savedPP = $ProgressPreference; $savedOE = $OutputEncoding+$savedCOE = $null; try { $savedCOE = [Console]::OutputEncoding } catch { }$ErrorActionPreference = 'Stop'$ProgressPreference = 'SilentlyContinue'try {@@ -50,6 +55,31 @@ function Say([string]$kind, [string]$msg, [string]$hint = '') {Write-Log ("[{0}] {1}{2}" -f $kind, $msg, $(if ($hint) { ' | Cách sửa: ' + $hint } else { '' }))}+# Chạy lệnh ngoài (winget/git/npm). PowerShell 5.1 với ErrorActionPreference=Stop biến MỌI dòng stderr (vd "npm warn",+# "From https://github.com/…" của git) thành lỗi dừng khi có 2>&1 → đặt Continue cục bộ, chỉ tin exit code.+# Ghi từng dòng vào log với tiền tố $tag. Trả @{ code; out }.+function Invoke-Native([string]$tag, [string]$exe, [string[]]$argv) {+ $ErrorActionPreference = 'Continue'+ $lines = New-Object System.Collections.Generic.List[string]+ $code = $null+ try {+ & $exe @argv 2>&1 | ForEach-Object { $l = [string]$_; $lines.Add($l); Write-Log (" ${tag}: " + $l) }+ $code = $LASTEXITCODE+ } catch {+ $lines.Add($_.Exception.Message); Write-Log (" ${tag}: " + $_.Exception.Message); $code = 1+ }+ if ($null -eq $code) { $code = 0 }+ return @{ code = [int]$code; out = $lines }+}++# Tag phát hành mới nhất (v*) trên GitHub, hoặc '' nếu chưa có tag nào / không đọc được.+function Get-LatestTag {+ $r = Invoke-Native 'git' 'git' @('ls-remote', '--tags', '--refs', '--sort=-v:refname', $Repo, 'v*')+ if ($r.code -ne 0) { return '' }+ foreach ($l in $r.out) { if ($l -match 'refs/tags/(v\S+)$') { return $Matches[1] } }+ return ''+}+function Update-SessionPath {$machine = [Environment]::GetEnvironmentVariable('Path', 'Machine')$user = [Environment]::GetEnvironmentVariable('Path', 'User')@@ -91,13 +121,11 @@ function Install-WingetPackage([string]$id, [string]$label) {$common = @('install', '--id', $id, '-e', '--silent', '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity')Say 'info' ("Đang cài $label qua winget ($id)…")Write-Log ("winget " + ($common -join ' ') + ' --scope user')- & winget @common --scope user 2>&1 | ForEach-Object { Write-Log (" winget: " + $_) }- $code = $LASTEXITCODE+ $code = (Invoke-Native 'winget' 'winget' ($common + @('--scope', 'user'))).codeif ($code -ne 0) {Write-Log ("winget --scope user thoát mã $code, thử cài cho cả máy")Say 'info' ("Bản cho riêng người dùng không có, cài cho cả máy (Windows có thể hỏi quyền admin, bấm Yes)…")- & winget @common 2>&1 | ForEach-Object { Write-Log (" winget: " + $_) }- $code = $LASTEXITCODE+ $code = (Invoke-Native 'winget' 'winget' $common).code}Update-SessionPathreturn $code@@ -156,7 +184,7 @@ function Invoke-Main {Say 'ok' ("PowerShell $($PSVersionTable.PSVersion)")if (-not [Environment]::Is64BitOperatingSystem) { Say 'fail' 'Windows 32-bit' 'LumReels cần Windows 64-bit.' }- $drive = (Split-Path -Qualifier $BaseDir)+ $drive = (Split-Path -Qualifier ([System.IO.Path]::GetFullPath($InstallDir)))try {$disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter ("DeviceID='{0}'" -f $drive)$freeGB = [math]::Round($disk.FreeSpace / 1GB, 1)@@ -211,36 +239,44 @@ function Invoke-Main {else { Say 'fail' ("$($d.label): cài không xong (winget mã $code)") ("Đóng cửa sổ này, mở lại LumReels-Setup.cmd (PATH mới chỉ có ở cửa sổ mới). Vẫn lỗi thì cài tay: " + $d.manual) }}- $needCore = (-not (Find-Exe 'git')) -or (-not (Get-NodeMajor))+ $n = Get-NodeMajor+ $needCore = (-not (Find-Exe 'git')) -or (-not $n) -or ($n.major -lt $MIN_NODE)if ($needCore -and -not $DryRun) {Say 'head' 'Dừng lại'- Say 'fail' 'Thiếu Node hoặc Git nên chưa lấy mã được' 'Sửa các mục ✗ ở trên rồi chạy lại bộ cài (chạy lại an toàn).'+ Say 'fail' "Thiếu Git hoặc Node $MIN_NODE+ nên chưa lấy mã được" 'Sửa các mục ✗ ở trên rồi chạy lại bộ cài (chạy lại an toàn).'return 1}# ---- 3. Mã LumReels ----Say 'head' '3. Mã LumReels'+ $want = $Ref+ if (-not $want) {+ if (Find-Exe 'git') { $want = Get-LatestTag }+ if ($want) { Say 'ok' "Bản phát hành mới nhất: $want" }+ else { Say 'warn' 'Repo chưa có tag phát hành (v*): dùng nhánh main, là mã mới nhất chưa qua phát hành' 'Muốn ghim bản cố định: install.ps1 -Ref <tag hoặc commit>' }+ } else { Say 'info' "Cài theo -Ref $want" }$isGit = Test-Path -LiteralPath (Join-Path $InstallDir '.git')$isEmpty = -not (Test-Path -LiteralPath $InstallDir) -or -not (Get-ChildItem -LiteralPath $InstallDir -Force -ErrorAction SilentlyContinue | Select-Object -First 1)if ($isGit) {- if ($DryRun) { Say 'plan' "Đã có ở $InstallDir → sẽ cập nhật: git pull --ff-only" }+ if ($DryRun) { Say 'plan' ("Đã có ở $InstallDir → sẽ cập nhật " + $(if ($want) { "về $want (git fetch + checkout)" } else { '(git pull --ff-only)' })) }else {- $out = & git -C $InstallDir pull --ff-only 2>&1- $out | ForEach-Object { Write-Log (" git: " + $_) }- if ($LASTEXITCODE -eq 0) { Say 'ok' "Đã cập nhật mã ở $InstallDir" }+ if ($want) {+ $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'fetch', '--quiet', '--tags', 'origin')+ if ($c.code -eq 0) { $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'checkout', '--quiet', $want) }+ # -Ref là tên nhánh: checkout xong thì kéo bản mới của nhánh đó+ if ($c.code -eq 0 -and (Invoke-Native 'git' 'git' @('-C', $InstallDir, 'symbolic-ref', '-q', 'HEAD')).code -eq 0) { $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'pull', '--ff-only', '--quiet') }+ } else { $c = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'pull', '--ff-only') }+ if ($c.code -eq 0) { Say 'ok' ("Đã cập nhật mã ở $InstallDir" + $(if ($want) { " ($want)" } else { '' })) }else { Say 'warn' 'Không cập nhật được (máy có sửa tay hoặc mất mạng), dùng bản đang có' "Tự gộp: cd `"$InstallDir`"; git stash; git pull; git stash pop" }}} elseif ($isEmpty) {- if ($DryRun) { Say 'plan' "Sẽ tải mã: git clone $Repo `"$InstallDir`"" }+ if ($DryRun) { Say 'plan' ("Sẽ tải mã: git clone $Repo `"$InstallDir`"" + $(if ($want) { " rồi checkout $want" } else { '' })) }else {New-Item -ItemType Directory -Force -Path (Split-Path -Parent $InstallDir) | Out-Null- $args2 = @('clone', '--quiet')- if ($Branch) { $args2 += @('--branch', $Branch) }- $args2 += @($Repo, $InstallDir)- $out = & git @args2 2>&1- $out | ForEach-Object { Write-Log (" git: " + $_) }- if ($LASTEXITCODE -eq 0) { Say 'ok' "Đã tải mã vào $InstallDir" }- else { Say 'fail' 'Tải mã từ GitHub lỗi' 'Kiểm tra mạng rồi chạy lại. Xem chi tiết trong install.log.'; return 1 }+ $r = Invoke-Native 'git' 'git' @('clone', '--quiet', $Repo, $InstallDir)+ if ($r.code -eq 0 -and $want) { $r = Invoke-Native 'git' 'git' @('-C', $InstallDir, 'checkout', '--quiet', $want) }+ if ($r.code -eq 0) { Say 'ok' ("Đã tải mã vào $InstallDir" + $(if ($want) { " ($want)" } else { '' })) }+ else { Say 'fail' 'Tải mã từ GitHub lỗi' 'Kiểm tra mạng (và -Ref có tồn tại không) rồi chạy lại. Xem chi tiết trong install.log.'; return 1 }}} else {Say 'fail' "Thư mục $InstallDir đã có file nhưng không phải bản clone git" 'Đổi tên/xoá thư mục đó, hoặc cài chỗ khác: install.ps1 -InstallDir <thư mục trống>'@@ -256,9 +292,7 @@ function Invoke-Main {Push-Location $InstallDirtry {Say 'info' 'Đang chạy npm install (lần đầu mất 2–5 phút)…'- $out = & npm.cmd install --no-audit --no-fund 2>&1- $code = $LASTEXITCODE- $out | ForEach-Object { Write-Log (" npm: " + $_) }+ $code = (Invoke-Native 'npm' 'npm.cmd' @('install', '--no-audit', '--no-fund')).codeif ($code -eq 0) { Say 'ok' 'Đã cài thư viện + font tiếng Việt' }else { Say 'fail' "npm install lỗi (mã $code)" "Xem install.log. Thử lại: cd `"$InstallDir`"; npm install" ; return 1 }} finally { Pop-Location }@@ -325,4 +359,6 @@ catch {}Write-Log ("Kết thúc, mã $code")# chạy qua `irm | iex` thì không exit (sẽ đóng luôn cửa sổ PowerShell của người dùng)+$ErrorActionPreference = $savedEAP; $ProgressPreference = $savedPP; $OutputEncoding = $savedOE+if ($savedCOE) { try { [Console]::OutputEncoding = $savedCOE } catch { } }if ($PSCommandPath) { exit $code }diff --git a/install/windows/start.ps1 b/install/windows/start.ps1index 8cd0efc..44b97ce 100644--- a/install/windows/start.ps1+++ b/install/windows/start.ps1@@ -55,6 +55,8 @@ if (-not (Test-LumReels)) {$deadline = (Get-Date).AddSeconds(90)while (-not (Test-LumReels)) {if ((Get-Date) -gt $deadline) {+ try { Stop-Process -Id $proc.Id -Force } catch { }+ Remove-Item -LiteralPath (Join-Path $BaseDir 'server.pid') -ErrorAction SilentlyContinueShow-Error "LumReels chưa bật được sau 90 giây.`nXem lỗi trong:`n$err"exit 1}diff --git a/install/windows/uninstall.ps1 b/install/windows/uninstall.ps1index 868cf01..84d2750 100644--- a/install/windows/uninstall.ps1+++ b/install/windows/uninstall.ps1@@ -3,7 +3,9 @@# Xoá: %LOCALAPPDATA%\LumReels (mã app, launcher, log) + shortcut Desktop/Start Menu; tắt server LumReels đang chạy từ đó.# GIỮ LẠI (trừ khi -Purge): ~/.lumreels (khoá AI đã nhập, giọng của tôi, gói mẫu, nháp)# và video đã dựng: jobs/, edits/ trong thư mục app được chuyển sang ~/.lumreels/backup-<ngày giờ>/ trước khi xoá.-# -Purge: xoá luôn ~/.lumreels và không giữ video đã dựng.+# -Purge: xoá luôn ~/.lumreels và không giữ video đã dựng. Chỉ xoá khi đường dẫn đúng dạng thư mục LumReels+# (tên chứa "lumreels", không phải gốc ổ / thư mục người dùng / hệ thống); LUMREELS_HOME đặt chỗ khác thì từ chối, tự xoá tay.+# Có bước lỗi → thoát mã 1.# Không gỡ Node, ffmpeg, Chrome, Git (máy có thể đang dùng cho việc khác): gỡ trong Settings > Apps nếu muốn.# File này phải lưu UTF-8 có BOM (Windows PowerShell 5.1 mới đọc đúng chữ có dấu).param([switch]$Purge, [switch]$Yes, [switch]$DryRun)@@ -16,20 +18,37 @@ $AppDir = Join-Path $BaseDir 'app'$UserData = $(if ($env:LUMREELS_HOME) { $env:LUMREELS_HOME } else { Join-Path $HOME '.lumreels' })$links = @((Join-Path ([Environment]::GetFolderPath('Desktop')) 'LumReels.lnk'), (Join-Path ([Environment]::GetFolderPath('Programs')) 'LumReels.lnk'))+$script:Failed = 0function Say([string]$kind, [string]$msg) {switch ($kind) {'ok' { Write-Host (' ✓ ' + $msg) -ForegroundColor Green }- 'fail' { Write-Host (' ✗ ' + $msg) -ForegroundColor Red }+ 'fail' { Write-Host (' ✗ ' + $msg) -ForegroundColor Red; $script:Failed++ }'plan' { Write-Host (' → ' + $msg) -ForegroundColor Cyan }default { Write-Host (' ' + $msg) }}}+# Thư mục dữ liệu được phép xoá bằng -Purge? Trả '' nếu được, hoặc lý do từ chối.+function Test-PurgeTarget([string]$dir) {+ try { $full = [System.IO.Path]::GetFullPath($dir).TrimEnd('\', '/') } catch { return 'đường dẫn không hợp lệ' }+ if (-not $full -or $full.Length -le 3) { return 'là gốc ổ đĩa' }+ $protected = @($HOME, $env:USERPROFILE, $env:LOCALAPPDATA, $env:APPDATA, $env:ProgramFiles, ${env:ProgramFiles(x86)}, $env:SystemRoot, $env:ProgramData, $env:PUBLIC,+ [Environment]::GetFolderPath('Desktop'), [Environment]::GetFolderPath('MyDocuments')) | Where-Object { $_ } | ForEach-Object { [System.IO.Path]::GetFullPath($_).TrimEnd('\', '/') }+ foreach ($p in $protected) {+ if ($full -ieq $p) { return "là thư mục hệ thống/người dùng ($p)" }+ if ($p.StartsWith($full + '\', [System.StringComparison]::OrdinalIgnoreCase)) { return "chứa thư mục hệ thống/người dùng ($p)" }+ }+ if ((Split-Path -Leaf $full) -notmatch 'lumreels') { return 'tên thư mục không có chữ "lumreels"' }+ return ''+}+Write-Host ''Write-Host 'Gỡ LumReels' -ForegroundColor Whiteif ($DryRun) { Write-Host '(chạy thử -DryRun: không xoá gì)' -ForegroundColor Cyan }Write-Host (" Sẽ xoá: $BaseDir và shortcut LumReels")-if ($Purge) { Write-Host (" -Purge: xoá luôn dữ liệu người dùng $UserData và video đã dựng") -ForegroundColor Yellow }+$purgeWhy = $(if ($Purge) { Test-PurgeTarget $UserData } else { '' })+if ($Purge -and $purgeWhy) { Say 'fail' "-Purge: KHÔNG xoá $UserData vì $purgeWhy. Kiểm tra biến LUMREELS_HOME, tự xoá tay nếu chắc chắn. Dừng, chưa gỡ gì."; if ($PSCommandPath) { exit 1 } else { return } }+elseif ($Purge) { Write-Host (" -Purge: xoá luôn dữ liệu người dùng $UserData và video đã dựng") -ForegroundColor Yellow }else { Write-Host (" Giữ lại: $UserData (khoá AI, giọng, gói mẫu) + video đã dựng") }if (-not $Yes -and -not $DryRun) {@@ -59,9 +78,11 @@ if (-not $Purge -and (Test-Path -LiteralPath $AppDir)) {foreach ($k in $keep) {if ($DryRun) { Say 'plan' "Sẽ chuyển $k → $bk" }else {- New-Item -ItemType Directory -Force -Path $bk | Out-Null- Move-Item -LiteralPath $k -Destination $bk- Say 'ok' "Đã giữ $(Split-Path -Leaf $k) ở $bk"+ try {+ New-Item -ItemType Directory -Force -Path $bk | Out-Null+ Move-Item -LiteralPath $k -Destination $bk+ Say 'ok' "Đã giữ $(Split-Path -Leaf $k) ở $bk"+ } catch { Say 'fail' ("Không chuyển được $k sang $bk (" + $_.Exception.Message + '). Dừng gỡ để không mất video.'); if ($PSCommandPath) { exit 1 } else { return } }}}}@@ -70,7 +91,7 @@ if (-not $Purge -and (Test-Path -LiteralPath $AppDir)) {# 3. shortcut + thư mục appforeach ($l in $links) {if (Test-Path -LiteralPath $l) {- if ($DryRun) { Say 'plan' "Sẽ xoá $l" } else { Remove-Item -LiteralPath $l -Force; Say 'ok' "Đã xoá $l" }+ if ($DryRun) { Say 'plan' "Sẽ xoá $l" } else { try { Remove-Item -LiteralPath $l -Force; Say 'ok' "Đã xoá $l" } catch { Say 'fail' "Không xoá được $l" } }}}if (Test-Path -LiteralPath $BaseDir) {@@ -82,11 +103,13 @@ if (Test-Path -LiteralPath $BaseDir) {} else { Say 'ok' 'Không còn thư mục app' }# 4. dữ liệu người dùng-if ($Purge -and (Test-Path -LiteralPath $UserData)) {+if ($Purge -and -not $purgeWhy -and (Test-Path -LiteralPath $UserData)) {if ($DryRun) { Say 'plan' "Sẽ xoá $UserData" }- else { Remove-Item -LiteralPath $UserData -Recurse -Force; Say 'ok' "Đã xoá $UserData" }+ else { try { Remove-Item -LiteralPath $UserData -Recurse -Force; Say 'ok' "Đã xoá $UserData" } catch { Say 'fail' ("Chưa xoá hết $UserData (" + $_.Exception.Message + ')') } }}Write-Host ''Say 'info' 'Node, ffmpeg, Chrome, Git vẫn giữ nguyên. Gỡ trong Settings > Apps nếu không dùng nữa.'-if ($PSCommandPath) { exit 0 }+$code = $(if ($script:Failed) { 1 } else { 0 })+if ($script:Failed) { Write-Host (" Có $($script:Failed) bước lỗi (xem ✗ ở trên).") -ForegroundColor Red }+if ($PSCommandPath) { exit $code }diff --git a/server/doctor.mjs b/server/doctor.mjsindex 7ab106a..b5675a2 100644--- a/server/doctor.mjs+++ b/server/doctor.mjs@@ -1,5 +1,6 @@// Màn "Kiểm tra máy": GET /api/doctor + nhập/kiểm khoá Anthropic.-// GET /api/doctor → { requiredOk, items[], key, jobsCount, firstVideo } (?refresh=1: dò lại giọng đọc)+// GET /api/doctor → { requiredOk, items[], key, jobsCount, videosCount, firstVideo } (?refresh=1: dò lại giọng đọc)+// chỉ nhận từ chính app (Origin / Sec-Fetch-Site), kết quả cache 30 s + gộp các lượt gọi trùng.// POST /api/doctor/key { key } → lưu khoá vào ~/.lumreels/credentials.json rồi kiểm ngay// POST /api/doctor/key/test → kiểm khoá đang dùng (GET /v1/models, không tốn token)// DELETE /api/doctor/key → xoá khoá đã nhập trong app (quay về biến môi trường / .env nếu có)@@ -8,10 +9,11 @@// KHÔNG trả khoá: chỉ 4 ký tự cuối. Không đọc file token của Claude Code: chỉ chạy `claude --version` và `claude auth status`.import fs from 'node:fs';import { execFile } from 'node:child_process';-import { ROOT, listJobs } from '../generator/jobs.mjs';+import path from 'node:path';+import { ROOT, JOBS, listJobs } from '../generator/jobs.mjs';import { findClaude, spawnClaude } from '../generator/claude.mjs';import { applyKeyPriority, keyInfo } from '../generator/config.mjs';-import { saveUserKey, removeUserKey, checkKey, cachedCheck, keyShapeOk } from '../generator/user-key.mjs';+import { saveUserKey, removeUserKey, checkKey, cachedCheck, keyShapeOk, readUserKey, credFileRestricted } from '../generator/user-key.mjs';import { ttsAvailable } from '../engine/audio/prefs.mjs';import { findChrome } from '../engine/fontcheck.mjs';import { stripSecrets } from '../engine/sandbox.mjs';@@ -101,9 +103,10 @@ async function checkClaude() {const [ver, st] = await Promise.all([run(['--version']), run(['auth', 'status', '--json'])]);const version = (/(\d+\.\d+\.\d+)/.exec(ver.out) || [])[1] || null;let loggedIn = null; let authMethod = null;- try { const j = JSON.parse(st.out.trim()); loggedIn = !!j.loggedIn; authMethod = typeof j.authMethod === 'string' ? j.authMethod.slice(0, 40) : null; } catch { /* bản cũ không có `auth status` */ }- const status = loggedIn === false ? 'warn' : 'ok';- return { id: 'claude', level: 'optional', status, installed: true, loggedIn, authMethod, value: version, fix: loggedIn === false ? FIX.claudeLogin : null };+ try { const j = JSON.parse(st.out.trim()); if (typeof j.loggedIn === 'boolean') loggedIn = j.loggedIn; authMethod = typeof j.authMethod === 'string' ? j.authMethod.slice(0, 40) : null; } catch { /* bản cũ không có `auth status` */ }+ // không đọc được trạng thái (bản cũ / lỗi) → "Chưa rõ", KHÔNG coi là đã đăng nhập+ const status = loggedIn === true ? 'ok' : 'warn';+ return { id: 'claude', level: 'optional', status, installed: true, loggedIn, authMethod, value: version, fix: loggedIn === true ? null : FIX.claudeLogin };}async function checkKeyItem({ deep = true } = {}) {@@ -111,8 +114,11 @@ async function checkKeyItem({ deep = true } = {}) {if (!info.present) return { id: 'apikey', level: 'optional', status: 'off', ...info, check: null, fix: { action: 'key', url: 'https://console.anthropic.com/settings/keys' } };const key = process.env.ANTHROPIC_API_KEY;const check = deep ? await checkKey(key) : cachedCheck(key);- const status = check?.valid === false ? 'bad' : check?.valid === true ? 'ok' : 'warn';- return { id: 'apikey', level: 'optional', status, ...info, check, fix: check?.valid === true ? null : { action: 'key', url: 'https://console.anthropic.com/settings/keys' } };+ // khoá nhập trong app mà file không siết được quyền (người khác trên máy đọc được) → cảnh báo+ const fileRestricted = info.source === 'app' ? credFileRestricted() : null;+ let status = check?.valid === false ? 'bad' : check?.valid === true ? 'ok' : 'warn';+ if (status === 'ok' && fileRestricted === false) status = 'warn';+ return { id: 'apikey', level: 'optional', status, ...info, check, fileRestricted, fix: check?.valid === true ? null : { action: 'key', url: 'https://console.anthropic.com/settings/keys' } };}function checkVoice(refresh) {@@ -145,34 +151,64 @@ export async function doctor({ refresh = false, deep = true } = {}) {const node = checkNode(); const chrome = checkChrome(); const disk = checkDisk(); const voice = checkVoice(refresh);// AI dựng cảnh (bắt buộc): khoá hợp lệ (hoặc chưa kiểm được) hoặc Claude Code đã đăng nhậpconst keyUsable = apikey.present && apikey.check?.valid !== false;- const claudeUsable = claude.installed && claude.loggedIn !== false;+ const claudeUsable = claude.installed && claude.loggedIn === true;const ai = {id: 'ai', level: 'required', status: keyUsable || claudeUsable ? 'ok' : 'missing',value: keyUsable ? 'api' : claudeUsable ? 'claude' : null,via: [keyUsable && 'api', claudeUsable && 'claude'].filter(Boolean),- reason: !keyUsable && !claudeUsable ? (apikey.present ? 'key_invalid' : claude.installed ? 'claude_logged_out' : 'none') : null,+ reason: !keyUsable && !claudeUsable ? (apikey.present ? 'key_invalid' : claude.installed ? (claude.loggedIn === null ? 'claude_unknown' : 'claude_logged_out') : 'none') : null,fix: keyUsable || claudeUsable ? null : { action: 'key', ...(claude.installed ? FIX.claudeLogin : FIX.claudeInstall) },};const items = [node, ffmpeg, chrome, disk, ai, apikey, claude, voice, git, ollama];- let jobsCount = 0;- try { jobsCount = listJobs().length; } catch { /* bỏ qua */ }+ let jobsCount = 0; let videosCount = 0;+ try {+ const jobs = listJobs();+ jobsCount = jobs.length;+ videosCount = jobs.filter((j) => j.status === 'done' && fs.existsSync(path.join(JOBS, j.id, 'out.mp4'))).length;+ } catch { /* bỏ qua */ }return {platform: process.platform,requiredOk: items.filter((i) => i.level === 'required').every((i) => i.status !== 'missing'),items,key: { ...keyInfo(), check: apikey.check || null },jobsCount,+ videosCount,firstVideo: FIRST_VIDEO,checkedAt: new Date().toISOString(),};}let lastKeyOp = 0;+const CACHE_MS = 30_000;+let cached = null; // { at, opts, data }+let inflight = null; // { key, promise }+/** Bỏ cache (khoá vừa đổi). */+export function invalidateDoctor() { cached = null; }+/** /api/doctor có cache 30 s và gộp các lượt gọi đang chạy dở (mỗi lượt spawn claude/ffmpeg/git/python). */+async function doctorCached({ refresh, deep }) {+ const key = `${refresh ? 1 : 0}${deep ? 1 : 0}`;+ if (!refresh && cached && cached.key === key && Date.now() - cached.at < CACHE_MS) return cached.data;+ if (inflight && (inflight.key === key || !refresh)) return inflight.promise;+ const promise = doctor({ refresh, deep }).then((data) => { cached = { at: Date.now(), key: `0${deep ? 1 : 0}`, data }; return data; }).finally(() => { inflight = null; });+ inflight = { key, promise };+ return promise;+}+/**+ * GET từ trang lạ cũng chạy được (img / fetch no-cors) → chỉ nhận khi là chính app: Origin (nếu có) phải hợp lệ,+ * Sec-Fetch-Site (nếu có) phải same-origin/none. Không có cả hai = curl/agent cục bộ → cho qua.+ */+function sameApp(req, originOk) {+ const site = String(req.headers['sec-fetch-site'] || '');+ if (site && !['same-origin', 'none'].includes(site)) return false;+ if (req.headers.origin !== undefined && !originOk(req)) return false;+ return true;+}/** Router. Trả true nếu đã xử lý. */-export async function handleDoctorRoute(req, res, p, url, { send, readBody }) {+export async function handleDoctorRoute(req, res, p, url, { send, readBody, originOk }) {if (!p.startsWith('/api/doctor')) return false;+ if (originOk && !sameApp(req, originOk)) { send(res, 403, { error: 'origin không hợp lệ' }); return true; }if (p === '/api/doctor' && req.method === 'GET') {- send(res, 200, await doctor({ refresh: url.searchParams.get('refresh') === '1', deep: url.searchParams.get('deep') !== '0' }));+ send(res, 200, await doctorCached({ refresh: url.searchParams.get('refresh') === '1', deep: url.searchParams.get('deep') !== '0' }));return true;}if (p === '/api/doctor/key' || p === '/api/doctor/key/test') {@@ -182,16 +218,18 @@ export async function handleDoctorRoute(req, res, p, url, { send, readBody }) {if (p === '/api/doctor/key' && req.method === 'DELETE') {const removed = removeUserKey();const info = applyKeyPriority();+ invalidateDoctor();console.log(`[doctor] xoá khoá trong app (${removed ? 'đã xoá' : 'không có'}); đang dùng: ${info.source || 'không có khoá'}`);send(res, 200, { removed, key: info });return true;}if (p === '/api/doctor/key') {const body = await readBody(req, 4096);- const k = String(body.key || '').trim();- if (!keyShapeOk(k)) { send(res, 400, { error: 'Khoá không đúng dạng: dán nguyên khoá bắt đầu bằng sk-ant-, không có dấu cách.', code: 'shape' }); return true; }+ const k = typeof body.key === 'string' ? body.key.trim() : '';+ if (!keyShapeOk(k) || !k.startsWith('sk-ant-')) { send(res, 400, { error: 'Khoá không đúng dạng: dán nguyên khoá bắt đầu bằng sk-ant-, không có dấu cách.', code: 'shape' }); return true; }const saved = saveUserKey(k);const info = applyKeyPriority();+ invalidateDoctor();const check = await checkKey(k, { fresh: true });console.log(`[doctor] lưu khoá trong app ${saved.hint} (siết quyền file: ${saved.restricted ? 'có' : 'không'}), kiểm: ${check.code}`);send(res, 200, { saved: true, restricted: saved.restricted, key: info, check });@@ -200,6 +238,7 @@ export async function handleDoctorRoute(req, res, p, url, { send, readBody }) {const info = keyInfo();if (!info.present) { send(res, 200, { key: info, check: { valid: false, status: null, code: 'missing' } }); return true; }const check = await checkKey(process.env.ANTHROPIC_API_KEY, { fresh: true });+ invalidateDoctor();console.log(`[doctor] kiểm khoá ${info.hint} (${info.source}): ${check.code}`);send(res, 200, { key: info, check });return true;diff --git a/server/public/doctor-panel.js b/server/public/doctor-panel.jsindex 9ec79d7..88460c8 100644--- a/server/public/doctor-panel.js+++ b/server/public/doctor-panel.js@@ -31,9 +31,13 @@'dr.ai.none': 'Cần một trong hai: khoá Anthropic (dán ở mục dưới) hoặc Claude Code đã đăng nhập.','dr.ai.key_invalid': 'Khoá Anthropic bị từ chối và chưa có Claude Code đăng nhập. Dán khoá mới ở mục dưới.','dr.ai.claude_logged_out': 'Claude Code chưa đăng nhập. Chạy lệnh dưới, hoặc dán khoá Anthropic.',+ 'dr.ai.claude_unknown': 'Chưa rõ Claude Code đã đăng nhập chưa (bản cũ hoặc lệnh kiểm lỗi). Chạy lệnh dưới để đăng nhập, hoặc dán khoá Anthropic.','dr.apikey.n': 'Khoá Anthropic API', 'dr.apikey.off': 'Trả theo lượt dùng, dựng nhanh nhất. Không có khoá thì dùng Claude Code.','dr.apikey.ok': 'Khoá {hint} hợp lệ ({src}).', 'dr.apikey.bad': 'Khoá {hint} ({src}) bị từ chối: sai, hết hạn hoặc đã thu hồi.', 'dr.apikey.warn': 'Chưa kiểm được khoá {hint} ({src}): mất mạng hoặc máy chủ bận.',- 'dr.claude.n': 'Claude Code', 'dr.claude.off': 'Dùng gói Claude Pro/Max thay khoá API. Cài xong chạy claude auth login.', 'dr.claude.ok': 'Đã cài, đã đăng nhập.', 'dr.claude.okNoAuth': 'Đã cài.', 'dr.claude.warn': 'Đã cài nhưng chưa đăng nhập.',+ 'dr.claude.n': 'Claude Code', 'dr.claude.off': 'Dùng gói Claude Pro/Max thay khoá API. Cài xong chạy claude auth login.', 'dr.claude.ok': 'Đã cài, đã đăng nhập.', 'dr.claude.okNoAuth': 'Đã cài.', 'dr.claude.warn': 'Đã cài nhưng chưa đăng nhập.', 'dr.claude.unknown': 'Đã cài, chưa rõ đã đăng nhập chưa. Chạy lệnh dưới để chắc chắn.',+ 'dr.apikey.unsafe': 'Khoá {hint} hợp lệ nhưng file khoá CHƯA được khoá quyền: tài khoản khác trên máy có thể đọc được. Xoá khoá trong app và dùng biến môi trường, hoặc tự chỉnh quyền file ~/.lumreels/credentials.json.',+ 'dr.key.unsafe': ' Lưu ý: không khoá được quyền file khoá, tài khoản khác trên máy có thể đọc được.',+ 'dr.key.shape': 'Khoá không đúng dạng: dán nguyên khoá bắt đầu bằng sk-ant-, không có dấu cách.','dr.voice.n': 'Giọng đọc', 'dr.voice.ok': 'Có giọng đọc chạy trên máy ({list}).', 'dr.voice.warn': 'Chỉ có edge-tts (cần mạng). Cài VieNeu để đọc tiếng Việt ngay trên máy.', 'dr.voice.off': 'Chưa có giọng đọc. Video vẫn có nhạc và tiếng động.','dr.git.n': 'Git', 'dr.git.ok': 'Để app tự cập nhật bản mới.', 'dr.git.off': 'Không có Git thì app không tự cập nhật được.','dr.ollama.n': 'Ollama', 'dr.ollama.ok': 'Đang chạy. Dành cho chế độ dựng không cần Claude (sắp có).', 'dr.ollama.warn': 'Đã cài nhưng chưa chạy.', 'dr.ollama.off': 'Chưa cần. Dành cho chế độ dựng không cần Claude (sắp có).',@@ -81,9 +85,13 @@'dr.ai.none': 'You need one of these: an Anthropic key (paste it below) or Claude Code signed in.','dr.ai.key_invalid': 'The Anthropic key was rejected and Claude Code is not signed in. Paste a new key below.','dr.ai.claude_logged_out': 'Claude Code is not signed in. Run the command below, or paste an Anthropic key.',+ 'dr.ai.claude_unknown': 'Not sure whether Claude Code is signed in (old version or the check failed). Run the command below to sign in, or paste an Anthropic key.','dr.apikey.n': 'Anthropic API key', 'dr.apikey.off': 'Pay per use, fastest builds. Without a key, Claude Code is used.','dr.apikey.ok': 'Key {hint} is valid ({src}).', 'dr.apikey.bad': 'Key {hint} ({src}) was rejected: wrong, expired or revoked.', 'dr.apikey.warn': 'Could not check key {hint} ({src}): offline or the server is busy.',- 'dr.claude.n': 'Claude Code', 'dr.claude.off': 'Use a Claude Pro/Max plan instead of an API key. After installing, run claude auth login.', 'dr.claude.ok': 'Installed and signed in.', 'dr.claude.okNoAuth': 'Installed.', 'dr.claude.warn': 'Installed but not signed in.',+ 'dr.claude.n': 'Claude Code', 'dr.claude.off': 'Use a Claude Pro/Max plan instead of an API key. After installing, run claude auth login.', 'dr.claude.ok': 'Installed and signed in.', 'dr.claude.okNoAuth': 'Installed.', 'dr.claude.warn': 'Installed but not signed in.', 'dr.claude.unknown': 'Installed; sign-in status unknown. Run the command below to make sure.',+ 'dr.apikey.unsafe': 'Key {hint} is valid but the key file could NOT be locked down: other accounts on this computer may read it. Remove the key from the app and use an environment variable, or fix the permissions of ~/.lumreels/credentials.json yourself.',+ 'dr.key.unsafe': ' Warning: the key file could not be locked down; other accounts on this computer may read it.',+ 'dr.key.shape': 'That does not look like a key: paste the whole key starting with sk-ant-, no spaces.','dr.voice.n': 'Voice-over', 'dr.voice.ok': 'Local voices available ({list}).', 'dr.voice.warn': 'Only edge-tts (needs internet). Install VieNeu for offline Vietnamese voices.', 'dr.voice.off': 'No voices yet. Videos still get music and sound effects.','dr.git.n': 'Git', 'dr.git.ok': 'Lets the app update itself.', 'dr.git.off': 'Without Git the app cannot update itself.','dr.ollama.n': 'Ollama', 'dr.ollama.ok': 'Running. For the upcoming no-Claude build mode.', 'dr.ollama.warn': 'Installed but not running.', 'dr.ollama.off': 'Not needed yet. For the upcoming no-Claude build mode.',@@ -171,7 +179,8 @@const v = { min: it.min, hint: it.hint || '', src: srcName(it.source), list: it.value || '' };switch (it.id) {case 'ai': return it.status === 'ok' ? t('dr.ai.ok.' + it.value) : t('dr.ai.' + (it.reason || 'none'));- case 'claude': return it.status === 'off' ? t('dr.claude.off') : it.status === 'warn' ? t('dr.claude.warn') : it.loggedIn ? t('dr.claude.ok') : t('dr.claude.okNoAuth');+ case 'claude': return it.status === 'off' ? t('dr.claude.off') : it.loggedIn === true ? t('dr.claude.ok') : it.loggedIn === false ? t('dr.claude.warn') : t('dr.claude.unknown');+ case 'apikey': return it.fileRestricted === false && it.check?.valid === true ? t('dr.apikey.unsafe', v) : t(`dr.apikey.${it.status}`, v);default: return t(`dr.${it.id}.${it.status}`, v);}}@@ -216,8 +225,12 @@try {const r = await fetch('/api/doctor/key', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key }) });const j = await r.json();- if (!r.ok) keyMsg = { cls: 'bad', text: I.srv(j.error) || t('dr.key.unknown', { status: r.status }) };- else { input.value = ''; report(j, true); window.dispatchEvent(new Event('lumreels:config')); }+ if (!r.ok) keyMsg = { cls: 'bad', text: j.code === 'shape' ? t('dr.key.shape') : I.srv(j.error) || t('dr.key.unknown', { status: r.status }) };+ else {+ input.value = ''; report(j, true);+ if (j.restricted === false) keyMsg = { cls: 'warn', text: keyMsg.text + t('dr.key.unsafe') };+ window.dispatchEvent(new Event('lumreels:config'));+ }} catch { keyMsg = { cls: 'bad', text: t('dr.loadErr') }; }await load({ quiet: true });document.getElementById('drKey')?.focus();@@ -330,7 +343,7 @@function renderCard() {if (!slot) return;const fv = data?.firstVideo;- const show = !!fv && data.requiredOk && !fvState.hidden && (fvState.forced || fvState.started || data.jobsCount === 0);+ const show = !!fv && data.requiredOk && !fvState.hidden && (fvState.forced || fvState.started || (data.videosCount ?? data.jobsCount) === 0);slot.hidden = !show;if (!show) { slot.replaceChildren(); return; }const hide = h('button.x.fv-x', { type: 'button', 'aria-label': t('fv.hide') }, '×');diff --git a/server/server.mjs b/server/server.mjsindex 4000c16..0688f5f 100644--- a/server/server.mjs+++ b/server/server.mjs@@ -258,7 +258,7 @@ const server = http.createServer(async (req, res) => {// ---- Tạo mẫu từ video (packs/drafts-http.mjs): job dựng thử đi qua hàng đợi chung ----if (await handleDraftRoute(req, res, p, { send, readBody, serveFile, allowedHosts: ALLOWED_HOSTS, runTest: draftTestRunner })) return;// ---- Kiểm tra máy + khoá Anthropic (server/doctor.mjs) ----- if (await handleDoctorRoute(req, res, p, url, { send, readBody })) return;+ if (await handleDoctorRoute(req, res, p, url, { send, readBody, originOk: (r) => originOk(r, ALLOWED_HOSTS) })) return;// ---- API ----if (p === '/api/templates' && req.method === 'GET') return send(res, 200, templateList());if (p === '/api/version' && req.method === 'GET') return send(res, 200, { version: PKG_VERSION, update: updateState });diff --git a/server/test/doctor-check.mjs b/server/test/doctor-check.mjsindex f64c4f0..2b25478 100644--- a/server/test/doctor-check.mjs+++ b/server/test/doctor-check.mjs@@ -59,6 +59,18 @@ ok(r401.ok === false && r401.authError === true && r401.status === 401, 'runApi:ok(/không hợp lệ/.test(r401.error) && /Kiểm tra máy/.test(r401.error) && !leaks(r401.error), 'runApi: câu lỗi dễ hiểu, không chứa khoá', r401.error);ok(/Claude Code/.test(authMessage(401, { claudeAvailable: true })), 'authMessage: có Claude Code → gợi ý chuyển Claude Code');+// V7: Claude Code có lệnh nhưng không đọc được `auth status` → loggedIn null = "Chưa rõ", không tính là dùng được+const fakeClaude = path.join(tmp, 'claude-cu.cmd');+fs.writeFileSync(fakeClaude, '@echo 1.0.0\r\n');+process.env.CLAUDE_BIN = fakeClaude;+const { doctor } = await import('../../server/doctor.mjs');+const dv = await doctor({ deep: true });+const cv = dv.items.find((i) => i.id === 'claude'); const av = dv.items.find((i) => i.id === 'ai');+ok(cv.installed === true && cv.loggedIn === null && cv.status === 'warn' && cv.fix?.cmd === 'claude auth login', 'V7: không đọc được auth status → Claude Code "Chưa rõ" (warn), có lệnh đăng nhập', JSON.stringify(cv));+ok(av.status === 'missing' && av.reason === 'key_invalid' && dv.requiredOk === false, 'V7: Chưa rõ đăng nhập + khoá sai → AI dựng cảnh thiếu, requiredOk=false', JSON.stringify(av));+ok(typeof dv.videosCount === 'number', 'có videosCount (thẻ Video đầu tiên theo video đã ra, không theo job)');+delete process.env.CLAUDE_BIN;+// ---- 2. server riêng ----const env = { ...process.env, PORT: String(PORT), LUMREELS_SKIP_UPDATE: '1', LUMREELS_HOME: lrHome, ANTHROPIC_API_KEY: '', ANTHROPIC_BASE_URL: MOCK,USERPROFILE: fakeHome, HOME: fakeHome, CLAUDE_BIN: path.join(tmp, 'khong-co-claude.exe') };@@ -89,7 +101,16 @@ try {ok(Array.isArray(j.items) && IDS.every((id) => j.items.some((i) => i.id === id)), 'đủ 10 mục', (j.items || []).map((i) => i.id).join(','));ok((j.items || []).every((i) => ['required', 'optional'].includes(i.level) && ['ok', 'missing', 'warn', 'off', 'bad'].includes(i.status) && (i.fix === null || typeof i.fix === 'object')), 'mỗi mục có level/status/fix đúng dạng');ok(['node', 'ffmpeg', 'chrome', 'disk', 'ai'].every((id) => j.items.find((i) => i.id === id)?.level === 'required'), 'node/ffmpeg/chrome/disk/ai là bắt buộc');- ok(typeof j.requiredOk === 'boolean' && typeof j.jobsCount === 'number' && typeof j.platform === 'string', 'requiredOk/jobsCount/platform');+ ok(typeof j.requiredOk === 'boolean' && typeof j.jobsCount === 'number' && typeof j.videosCount === 'number' && typeof j.platform === 'string', 'requiredOk/jobsCount/videosCount/platform');+ // V3: GET /api/doctor chỉ nhận từ chính app + cache 30 s+ const ev = await req('GET', '/api/doctor', undefined, { Origin: 'https://evil.example' });+ ok(ev.status === 403, 'V3: GET /api/doctor từ Origin lạ → 403', ev.status);+ const cs = await req('GET', '/api/doctor', undefined, { 'Sec-Fetch-Site': 'cross-site' });+ ok(cs.status === 403, 'V3: GET /api/doctor Sec-Fetch-Site cross-site (img/no-cors) → 403', cs.status);+ const so = await req('GET', '/api/doctor', undefined, { 'Sec-Fetch-Site': 'same-origin', Origin: `http://127.0.0.1:${PORT}` });+ ok(so.status === 200, 'V3: GET từ chính app (same-origin) → 200', so.status);+ const t0 = Date.now(); const c2 = await req('GET', '/api/doctor'); const dt = Date.now() - t0;+ ok(c2.json?.checkedAt === j.checkedAt && dt < 500, 'V3: gọi lại trong 30 s dùng kết quả cache (không spawn lại)', `${dt} ms`);ok(j.firstVideo?.templateId === '009' && j.firstVideo.aspect === '9:16' && j.firstVideo.durationS >= 8 && j.firstVideo.durationS <= 15 && /[ạảãàáâậầấẩẫăắằặẳẵ]/.test(j.firstVideo.content?.vi || ''), 'firstVideo: mẫu 009, 9:16, 8–15 s, nội dung tiếng Việt');const ai1 = j.items.find((i) => i.id === 'ai');ok(j.key?.present === false && ai1.status === 'missing' && j.requiredOk === false, 'không khoá + không Claude Code → AI dựng cảnh thiếu, requiredOk=false', JSON.stringify({ key: j.key, ai: ai1 }));@@ -100,7 +121,13 @@ try {ok(bad.status === 403 && !fs.existsSync(path.join(lrHome, 'credentials.json')), 'Origin lạ → 403, không lưu khoá', bad.status);await sleep(1600);const shape = await req('POST', '/api/doctor/key', { key: 'abc def' });- ok(shape.status === 400, 'khoá sai dạng → 400', shape.status);+ ok(shape.status === 400 && shape.json?.code === 'shape', 'khoá sai dạng → 400, code=shape (client tự dịch)', shape.status);+ await sleep(1600);+ const arr = await req('POST', '/api/doctor/key', { key: [FAKE] });+ ok(arr.status === 400, 'khoá gửi dạng mảng → 400', arr.status);+ await sleep(1600);+ const nopfx = await req('POST', '/api/doctor/key', { key: 'abcdefghijklmnopqrstuvwxyz0123456789' });+ ok(nopfx.status === 400, 'khoá không bắt đầu bằng sk-ant- → 400', nopfx.status);// khoá giả → không hợp lệawait sleep(1600);@@ -115,7 +142,9 @@ try {const acl = spawnSync('icacls', [credFile], { encoding: 'utf8' }).stdout;ok(!/Everyone|BUILTIN\\Users|Authenticated Users|Administrators/i.test(acl) && new RegExp(process.env.USERNAME, 'i').test(acl), 'file khoá: chỉ người dùng (+SYSTEM) có quyền', acl.trim());} else ok((fs.statSync(credFile).mode & 0o077) === 0, 'file khoá chmod 600');+ ok(s1.json?.restricted === true, 'V4: báo đã siết quyền file khoá (restricted=true)');const d2 = await req('GET', '/api/doctor');+ ok(d2.json?.items?.find((i) => i.id === 'apikey')?.fileRestricted === true, 'V4: Kiểm tra máy đọc lại quyền file khoá (fileRestricted=true)');ok(d2.json?.items?.find((i) => i.id === 'apikey')?.status === 'bad' && d2.json.items.find((i) => i.id === 'ai').status === 'missing', 'Kiểm tra máy: khoá giả = Sai khoá, AI vẫn thiếu');ok(!leaks(d2.text), 'GET /api/doctor không chứa khoá');@@ -153,6 +182,7 @@ if (process.argv.includes('--live')) {delete process.env.ANTHROPIC_BASE_URL;const r = await checkKey(FAKE, { fresh: true });ok(r.valid === false && r.status === 401, 'live: khoá giả gọi api.anthropic.com → 401, không hợp lệ', JSON.stringify(r));+ await sleep(1500); // Node/Windows: để socket TLS đóng xong trước khi thoát (tránh assert libuv lúc exit)}console.log(`\n${pass} PASS, ${fail} FAIL`);