WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
修复安全漏洞和其他问题,导出账号需设置密码
[email protected]603127eaea51
diff --git a/AGENTS.md b/AGENTS.mdindex 030605a..5a70e43 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -71,6 +71,13 @@ The injected panel is a compact WorkBuddy-native tool surface, not a marketing p- Windows file replacement must account for locks held by running `launcher.cmd`/`cmd.exe`. Do not kill broad process names such as every `Electron` process; match the intended executable/path narrowly.- If a launcher or daemon update changes code loaded into a long-running process, use a version/build bump so the launcher cannot reuse stale in-memory code.+## Release Version Consistency++- A release version must be identical in the package filename, macOS `Info.plist` (`CFBundleShortVersionString`/`CFBundleVersion`), and the packaged `scripts/daemon.js` `DAEMON_VERSION`. A package named `1.0.10` that runs daemon code reporting `1.0.6` is invalid.+- Build scripts must always rewrite the staged daemon version from the release `VERSION`; never rely on the version embedded in the reusable `WorkDaddy.app` shell or on a conditional test-only override.+- Before publishing or handing off a package, inspect the actual DMG/ZIP contents and record the daemon version, app metadata version, profile branding, and required update scripts. Do not infer package correctness from the filename alone.+- The updater must reject an artifact whose internal daemon version does not match the GitHub release target, and must leave a local diagnostic trail showing the selected asset, expected version, internal version, and installation attempt ID.+## Change Workflow1. Read the surrounding code and existing tests before editing.diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1index 3b24b3b..01ba249 100644--- a/scripts/apply-update.ps1+++ b/scripts/apply-update.ps1@@ -164,6 +164,17 @@ try {foreach ($required in @('scripts\daemon.js', 'scripts\launcher.cmd', 'scripts\win-launcher.js')) {if (-not (Test-Path (Join-Path $srcRoot $required) -PathType Leaf)) { throw "更新包缺少 $required" }}+ $sourceDaemonText = Get-Content -LiteralPath (Join-Path $srcRoot 'scripts\daemon.js') -Raw+ $sourceDaemonMatch = [regex]::Match($sourceDaemonText, "const DAEMON_VERSION = '([^']+)'")+ $sourceDaemonVersion = if ($sourceDaemonMatch.Success) { $sourceDaemonMatch.Groups[1].Value } else { '' }+ $packageName = [IO.Path]::GetFileNameWithoutExtension($SrcZip)+ $packageVersionMatch = [regex]::Match($packageName, '([0-9]+\.[0-9]+\.[0-9]+)')+ $packageVersion = if ($packageVersionMatch.Success) { $packageVersionMatch.Groups[1].Value } else { '' }+ Write-ApplyLog "artifact inspect package=$packageName packageVersion=$packageVersion daemonVersion=$sourceDaemonVersion"+ if ([string]::IsNullOrWhiteSpace($sourceDaemonVersion)) { throw '更新包 daemon.js 缺少 DAEMON_VERSION' }+ if (-not [string]::IsNullOrWhiteSpace($packageVersion) -and $sourceDaemonVersion -ne $packageVersion) {+ throw "更新包内部 daemon 版本 $sourceDaemonVersion 与文件目标版本 $packageVersion 不一致"+ }New-Item -ItemType Directory -Force -Path $AppDir | Out-Null& robocopy $srcRoot $AppDir /MIR /NFL /NDL /NJH /NJS /NP | Out-Null@@ -188,6 +199,11 @@ try {Start-Sleep -Seconds 1}if (-not $ready) { throw '新版 daemon 在 60 秒内未就绪' }+ $runningVersion = [string]$status.version+ Write-ApplyLog "running daemon version=$runningVersion expected=$packageVersion"+ if (-not [string]::IsNullOrWhiteSpace($packageVersion) -and $runningVersion -ne $packageVersion) {+ throw "新版 daemon 实际版本 $runningVersion 与目标版本 $packageVersion 不一致"+ }if (Test-Path -LiteralPath $oldDir) {Remove-Item -LiteralPath $oldDir -Recurse -Force -ErrorAction SilentlyContinuediff --git a/scripts/apply-update.sh b/scripts/apply-update.shindex 0a0f915..ef39d19 100644--- a/scripts/apply-update.sh+++ b/scripts/apply-update.sh@@ -8,7 +8,8 @@ APP_PATH="${2:?缺少目标 app 路径}"UI_PORT="${3:-47832}"LOG="${4:-$HOME/Library/Application Support/WorkDaddy/update/apply.log}"ATTEMPT_ID="${5:-unknown}"-LABEL="com.workbuddy.workdaddy"+PROFILE="${6:-workbuddy-cn}"+LABEL="com.workbuddy.workdaddy.${PROFILE}"mkdir -p "$(dirname "$LOG")"exec >>"$LOG" 2>&1@@ -32,13 +33,47 @@ log "start attempt=$ATTEMPT_ID src=$SRC_APP dst=$APP_PATH port=$UI_PORT pid=$$"[ -f "$SRC_APP/Contents/Info.plist" ] || fail "源应用缺少 Contents/Info.plist" 11[ -f "$SRC_APP/Contents/Resources/scripts/daemon.js" ] || fail "源应用缺少 daemon.js" 12[ -x "$SRC_APP/Contents/MacOS/launcher" ] || fail "源应用 launcher 不可执行" 13+SRC_DAEMON_VERSION="$(grep -o "const DAEMON_VERSION = '[^']*'" "$SRC_APP/Contents/Resources/scripts/daemon.js" | head -1 || true)"+log "source daemon version=$SRC_DAEMON_VERSION profile=$PROFILE"-# KeepAlive/launchd 是异步的;先停服务,再按进程和端口确认旧 daemon 已退出。+# KeepAlive/launchd 是异步的;先停服务,再只终止当前 WorkDaddy app 的 daemon。UID_NUM="$(id -u)"launchctl bootout "gui/$UID_NUM/$LABEL" 2>&1 || log "launchctl bootout 返回非零(可能本来未注册)"launchctl remove "$LABEL" 2>&1 || log "launchctl remove 返回非零(可能本来未注册)"-pkill -f "$APP_PATH/Contents/Resources/scripts/daemon.js" 2>&1 || true-pkill -f "WorkDaddy.app/Contents/Resources/scripts/daemon.js" 2>&1 || true++daemon_pids() {+ ps -axo pid=,command= | awk -v app="$APP_PATH/Contents/Resources/scripts/daemon.js" -v self="$$" \+ '$1 != self && index($0, app) { print $1 }'+}+stop_daemons() {+ local pids pid+ pids="$(daemon_pids || true)"+ if [ -z "$pids" ]; then+ log "未发现当前 app 的 daemon 进程"+ return 0+ fi+ log "发现 daemon pid(s): $(printf '%s' "$pids" | tr '\n' ' ')"+ while read -r pid; do+ [ -n "$pid" ] || continue+ log "发送 TERM 到 daemon pid=$pid"+ kill -TERM "$pid" 2>&1 || log "TERM 失败 pid=$pid(可能已退出)"+ done <<EOF+$pids+EOF+ for _ in $(seq 1 10); do+ [ -z "$(daemon_pids || true)" ] && return 0+ sleep 1+ done+ pids="$(daemon_pids || true)"+ while read -r pid; do+ [ -n "$pid" ] || continue+ log "TERM 后仍存活,发送 KILL 到 daemon pid=$pid"+ kill -KILL "$pid" 2>&1 || true+ done <<EOF+$pids+EOF+}+stop_daemonsPORT_READY=0for i in $(seq 1 30); do@@ -59,7 +94,7 @@ firollback() {local code="${1:-30}"log "开始回滚 code=$code"- pkill -f "$APP_PATH/Contents/Resources/scripts/daemon.js" 2>&1 || true+ stop_daemonsrm -rf "$APP_PATH" || trueif [ -e "$OLD_PATH" ]; thenmv "$OLD_PATH" "$APP_PATH" || log "回滚失败: $OLD_PATH -> $APP_PATH"@@ -74,6 +109,8 @@ mkdir -p "$(dirname "$APP_PATH")"cp -R "$SRC_APP" "$APP_PATH" || rollback 22chmod -R u+rwX "$APP_PATH" || rollback 23xattr -cr "$APP_PATH" 2>&1 || log "清除隔离属性失败(继续,可能已无隔离属性)"+TARGET_DAEMON_VERSION="$(grep -o "const DAEMON_VERSION = '[^']*'" "$APP_PATH/Contents/Resources/scripts/daemon.js" | head -1 || true)"+log "target daemon version=$TARGET_DAEMON_VERSION"[ -f "$APP_PATH/Contents/Info.plist" ] || rollback 24[ -f "$APP_PATH/Contents/Resources/scripts/daemon.js" ] || rollback 25diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.shindex 5aa1bb4..6560234 100644--- a/scripts/build-mac-dmg.sh+++ b/scripts/build-mac-dmg.sh@@ -64,9 +64,13 @@ if [ "$PROFILE" = "workbuddy-ai" ]; thenperl -0pi -e 's/<string>WorkDaddy<\/string>/<string>WorkDaddy AI<\/string>/g' "$PACKAGE_APP/Contents/Info.plist"fiperl -0pi -e "s/<string>1\\.0\\.8<\\/string>/<string>${VERSION}<\\/string>/g; s/<string>108<\\/string>/<string>${VERSION_CODE}<\\/string>/g" "$PACKAGE_APP/Contents/Info.plist"-if [ -n "${WORKDADDY_BUILD_VERSION:-}" ]; then- perl -0pi -e "s/(const DAEMON_VERSION = ')[^']+(';)/\${1}${VERSION}\${2}/" \- "$PACKAGE_APP/Contents/Resources/scripts/daemon.js"+# 无论源码壳当前版本如何,每次产物都必须让 daemon 版本与安装包版本一致。+perl -0pi -e "s/(const DAEMON_VERSION = ')[^']+(';)/\${1}${VERSION}\${2}/" \+ "$PACKAGE_APP/Contents/Resources/scripts/daemon.js"+# app 壳可能携带滞后的 package.json;同步版本元数据,避免旧值覆盖关于页/诊断信息。+if [ -f "$PACKAGE_APP/Contents/Resources/scripts/package.json" ]; then+ perl -0pi -e "s/(\"version\"\s*:\s*\")([^\"]+)(\")/\${1}${VERSION}\${3}/" \+ "$PACKAGE_APP/Contents/Resources/scripts/package.json"filn -s /Applications "$STAGE/Applications"cat > "$STAGE/安装失败自主解决提示词.txt" <<'EOF'diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.shindex 8ba2afe..7fe80a9 100644--- a/scripts/build-win-zip.sh+++ b/scripts/build-win-zip.sh@@ -15,7 +15,7 @@ elsewinpath() { printf '%s\n' "$1"; }fi-VERSION="$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)"+VERSION="${WORKDADDY_BUILD_VERSION:-$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)}"PROFILE="${WORKDADDY_BUILD_PROFILE:-}"if [ -z "$PROFILE" ]; thenfor profile in workbuddy-cn workbuddy-ai; do@@ -76,12 +76,14 @@ cp -R scripts "$STAGE/scripts"# 绝不能全局替换 __WBS_DEFAULT_PROFILE__ —— 否则判断条件# $Profile -eq '__WBS_DEFAULT_PROFILE__' 会被替换成 $Profile -eq 'workbuddy-ai',# 让 AI 包默认 profile 自身触发"回退到 workbuddy-cn",桌面快捷方式名/安装目录全部错乱。-PROFILE="$PROFILE" python3 - "$(winpath "$STAGE/scripts")" <<'PY'+PROFILE="$PROFILE" BUILD_VERSION="$VERSION" python3 - "$(winpath "$STAGE/scripts")" <<'PY'import os+import reimport sysscripts = sys.argv[1]profile = os.environ['PROFILE']+build_version = os.environ.get('BUILD_VERSION', '')# win-launcher.js:默认 profile(仅当源码仍是 || 'workbuddy-cn' 时替换)wl = os.path.join(scripts, 'win-launcher.js')@@ -94,6 +96,24 @@ if old in s:with open(wl, 'w', encoding='utf-8', newline='') as f:f.write(s)+# 每个产物都强制同步 daemon 版本,避免 app 壳残留旧 daemon(例如 1.0.6)导致+# 文件名/Info.plist 是新版本但实际运行代码仍报告旧版本。+daemon = os.path.join(scripts, 'daemon.js')+with open(daemon, encoding='utf-8') as f:+ s = f.read()+s = re.sub(r"(const DAEMON_VERSION = ')[^']+(';)", r"\g<1>" + build_version + r"\g<2>", s, count=1)+with open(daemon, 'w', encoding='utf-8', newline='') as f:+ f.write(s)++# 同步可选 package.json 的版本元数据,避免旧壳版本覆盖关于页展示。+package_json = os.path.join(scripts, 'package.json')+if build_version and os.path.exists(package_json):+ with open(package_json, encoding='utf-8') as f:+ s = f.read()+ s = re.sub(r'("version"\s*:\s*")[^"]+(")', r'\g<1>' + build_version + r'\g<2>', s, count=1)+ with open(package_json, 'w', encoding='utf-8', newline='') as f:+ f.write(s)+# 三个 ps1:只替换 param 默认值([string]$Profile = '__WBS_DEFAULT_PROFILE__')。# 写回必须用 utf-8-sig(保留 UTF-8 BOM):源 ps1 带 BOM,Windows PowerShell/ISE 依赖# BOM 识别 UTF-8;一旦写成无 BOM 的 UTF-8,会被按 ANSI 代码页解析中文 → 乱码语法报错。diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 8a1c844..19e5a9c 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -136,8 +136,9 @@ const DATA_DIR = defaultDataDir();// 1.0.21:模型页改为当前/备选模型列表风格,去除刷新入口并优化字段排版// 1.0.9:WorkBuddy / WorkBuddy AI profile 隔离;修复 Windows launcher 的本地端口探测、// AI 端 CDP 误连国内端、watchdog 路径和退出确认问题。-const DAEMON_VERSION = '1.0.9';-const DAEMON_BUILD_ID = 'release-1.0.9-20260823-hotfix7';+// 1.0.13:下载使用唯一临时文件并在校验通过后原子替换,防止并发更新造成 ENOENT。+const DAEMON_VERSION = '1.0.13';+const DAEMON_BUILD_ID = 'release-1.0.13-20260823-security4';const HOST = '127.0.0.1';const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app@@ -151,10 +152,37 @@ const CDP_PORT_HINT = process.env.WBSWITCH_CDP_PORT? parseInt(process.env.WBSWITCH_CDP_PORT, 10): (PROFILE_CDP_PORT[PROFILE.id] || null);const CDP_PORT_FILE = path.join(DATA_DIR, 'cdp-port.json');+const API_TOKEN_FILE = path.join(DATA_DIR, '.api-token');const WATCH_INTERVAL = 3000; // 文件监听兜底const BACKUP_DEBOUNCE = 1500; // CDP 事件触发的备份防抖const CDP_RECONNECT_MS = 5000;+// API token 是当前 profile 的本地能力凭证:只注入 WorkBuddy renderer,不写日志、不回传状态接口。+// 用 wx + 重读避免两个 watchdog 进程启动竞态时各自生成一枚 token。+function loadApiToken() {+ const valid = (value) => /^[a-f0-9]{64}$/i.test(String(value || '').trim());+ try {+ const current = fs.readFileSync(API_TOKEN_FILE, 'utf8').trim();+ if (valid(current)) return current;+ } catch (_) {}+ try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (_) {}+ const generated = crypto.randomBytes(32).toString('hex');+ try {+ fs.writeFileSync(API_TOKEN_FILE, generated + '\n', { encoding: 'utf8', mode: 0o600, flag: 'wx' });+ try { fs.chmodSync(API_TOKEN_FILE, 0o600); } catch (_) {}+ return generated;+ } catch (_) {+ try {+ const existing = fs.readFileSync(API_TOKEN_FILE, 'utf8').trim();+ if (valid(existing)) return existing;+ } catch (_) {}+ // 极端情况下数据目录不可写:只在内存中继续运行,启动器会从注入面板路径恢复;不记录 token。+ return generated;+ }+}++const API_TOKEN = loadApiToken();+function validCdpPort(port) {return Number.isInteger(port) && port >= 1024 && port <= 65535;}@@ -238,19 +266,58 @@ const UPDATE_REQ_TIMEOUT = 10000; // 网络超时,超时静默失败不阻塞const UPDATE_DIR = path.join(DATA_DIR, 'update'); // 下载/解包目录const UPDATE_CHECK_CACHE = path.join(DATA_DIR, 'update-check.json');const UPDATE_ATTEMPT_FILE = path.join(UPDATE_DIR, 'last-attempt.json');+const UPDATE_DEBUG_LOG = path.join(UPDATE_DIR, 'update-debug.log');// 更新状态机(面板轮询用):idle | checking | downloading | verifying | installing | done | errorconst updateState = {status: 'idle',latest: null,hasUpdate: false,+ assetName: null,+ dmgSha256: null,downloaded: false,progress: 0, // 0-100+ downloadedBytes: 0,+ totalBytes: 0,+ downloadRate: 0,+ etaSeconds: null,message: '',error: null,checkedAt: 0,attemptId: null,};let updateTimer = null;+let updateDownloadPromise = null;++function updateDebug(stage, details) {+ const scrub = (value, key = '') => {+ const lower = String(key).toLowerCase();+ if (/token|cookie|authorization|secret|password|private.?key|access.?token/.test(lower)) return '[redacted]';+ if (typeof value === 'string') return value.length > 1200 ? value.slice(0, 1200) + '…' : value;+ if (Array.isArray(value)) return value.map((item) => scrub(item));+ if (value && typeof value === 'object') {+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, scrub(v, k)]));+ }+ return value;+ };+ const entry = {+ at: new Date().toISOString(),+ stage,+ profile: PROFILE.id,+ client: PROFILE.name,+ daemonVersion: DAEMON_VERSION,+ buildId: DAEMON_BUILD_ID,+ ...scrub(details || {}),+ };+ try {+ fs.mkdirSync(UPDATE_DIR, { recursive: true });+ try {+ if (fs.statSync(UPDATE_DEBUG_LOG).size > 2 * 1024 * 1024) {+ fs.renameSync(UPDATE_DEBUG_LOG, UPDATE_DEBUG_LOG + '.1');+ }+ } catch (_) {}+ fs.appendFileSync(UPDATE_DEBUG_LOG, JSON.stringify(entry) + '\n', { encoding: 'utf8', mode: 0o600 });+ } catch (_) {}+}function writeUpdateAttempt(attempt) {try {@@ -303,6 +370,15 @@ function parseSha256(body) {return m ? m[1].toLowerCase() : null;}+function normalizeAssetSha256(value) {+ const text = String(value || '').trim().replace(/^sha256:/i, '');+ return /^[a-fA-F0-9]{64}$/.test(text) ? text.toLowerCase() : null;+}++function expectedUpdateSha256() {+ return updateState.dmgSha256 || parseSha256(updateState.notes);+}+// 检查更新:请求 Releases API,比对版本,结果写缓存(内存 + 文件)function checkUpdate(force) {if (!force && updateTimer) {@@ -313,6 +389,7 @@ function checkUpdate(force) {}updateState.status = 'checking';updateState.message = '正在检查更新…';+ updateDebug('check-start', { force: !!force, current: DAEMON_VERSION, updateApi: UPDATE_API });return httpsGet(UPDATE_API).then(({ status, body }) => {if (status !== 200) {@@ -338,11 +415,14 @@ function checkUpdate(force) {assets.find((a) => /\.dmg$/i.test(a.name || '') && (PROFILE.id !== 'workbuddy-ai' || !/WorkDaddy-AI-/i.test(a.name || ''))) || null);updateState.dmgUrl = asset ? asset.browser_download_url : null;updateState.dmgSize = asset ? asset.size : 0;+ updateState.dmgSha256 = asset ? normalizeAssetSha256(asset.digest) : parseSha256(updateState.notes);+ updateState.assetName = asset ? asset.name : null;updateState.checkedAt = Date.now();updateState.status = 'idle';updateState.message = updateState.hasUpdate ? '发现新版本 v' + latest : '已是最新版本';- try { fs.writeFileSync(UPDATE_CHECK_CACHE, JSON.stringify({ latest, hasUpdate: updateState.hasUpdate, dmgUrl: updateState.dmgUrl, dmgSize: updateState.dmgSize, notes: updateState.notes, checkedAt: updateState.checkedAt })); } catch (_) {}+ try { fs.writeFileSync(UPDATE_CHECK_CACHE, JSON.stringify({ latest, hasUpdate: updateState.hasUpdate, dmgUrl: updateState.dmgUrl, dmgSize: updateState.dmgSize, dmgSha256: updateState.dmgSha256, assetName: updateState.assetName, notes: updateState.notes, checkedAt: updateState.checkedAt })); } catch (_) {}log(`[update] 检查完成: latest=${latest} hasUpdate=${updateState.hasUpdate} (current=${DAEMON_VERSION})`);+ updateDebug('check-result', { current: DAEMON_VERSION, latest, hasUpdate: updateState.hasUpdate, assetName: updateState.assetName, assetSize: updateState.dmgSize, assetSha256: updateState.dmgSha256 });return updateState;}).catch((e) => {@@ -350,6 +430,7 @@ function checkUpdate(force) {updateState.error = e.message;updateState.message = '检查更新失败';log(`[update] 检查失败: ${e.message}`);+ updateDebug('check-error', { error: e.message });// 尝试读缓存兜底(上次成功的结果)try {const c = JSON.parse(fs.readFileSync(UPDATE_CHECK_CACHE, 'utf8'));@@ -357,6 +438,8 @@ function checkUpdate(force) {updateState.hasUpdate = !!c.hasUpdate;updateState.dmgUrl = c.dmgUrl;updateState.dmgSize = Number(c.dmgSize) || 0;+ updateState.assetName = c.assetName || null;+ updateState.dmgSha256 = normalizeAssetSha256(c.dmgSha256) || parseSha256(c.notes);updateState.notes = c.notes;updateState.checkedAt = c.checkedAt || Date.now();} catch (_) {}@@ -365,22 +448,60 @@ function checkUpdate(force) {}// 下载安装包(macOS .dmg / Windows .zip),流式写文件更新 progress,带 SHA-256 校验+// 同一 daemon 内只允许一个下载流程,避免并发请求互相删除/覆盖固定目标文件。function downloadUpdate() {- if (!updateState.dmgUrl) return Promise.reject(new Error('无可用安装包'));+ if (updateDownloadPromise) return updateDownloadPromise;+ updateDownloadPromise = Promise.resolve()+ .then(() => downloadUpdateInternal())+ .finally(() => { updateDownloadPromise = null; });+ return updateDownloadPromise;+}++function downloadUpdateInternal() {+ if (!updateState.dmgUrl) {+ updateDebug('download-error', { error: '无可用安装包', latest: updateState.latest, assetName: updateState.assetName });+ return Promise.reject(new Error('无可用安装包'));+ }fs.mkdirSync(UPDATE_DIR, { recursive: true });updateState.downloaded = false;updateState.error = null;+ updateState.downloadedBytes = 0;+ updateState.totalBytes = Number(updateState.dmgSize) || 0;+ updateState.downloadRate = 0;+ updateState.etaSeconds = null;const ext = IS_WIN ? '.zip' : '.dmg';const updatePrefix = PROFILE.id === 'workbuddy-ai' ? 'WorkDaddy-AI-' : 'WorkDaddy-';const target = path.join(UPDATE_DIR, updatePrefix + updateState.latest + ext);+ const tempTarget = target + '.part.' + process.pid + '.' + crypto.randomBytes(8).toString('hex');+ const expectSha = expectedUpdateSha256();+ updateDebug('download-start', {+ latest: updateState.latest,+ assetName: updateState.assetName,+ target: path.basename(target),+ tempTarget: path.basename(tempTarget),+ expectedSha256: expectSha,+ expectedSize: updateState.dmgSize,+ });+ if (!expectSha) {+ const error = new Error('发布未提供可信的 SHA-256,已停止更新');+ updateState.status = 'error';+ updateState.error = error.message;+ updateState.message = '安装包缺少完整性校验,已停止更新';+ updateDebug('download-error', { stage: 'preflight', error: error.message, target: path.basename(target) });+ return Promise.reject(error);+ }if (fs.existsSync(target)) {- const expect = parseSha256(updateState.notes);- const checked = validateUpdateArtifact(target, expect);+ const checked = validateUpdateArtifact(target, expectSha);if (checked.ok) {updateState.downloaded = true;updateState.progress = 100;+ updateState.downloadedBytes = fs.statSync(target).size;+ updateState.totalBytes = updateState.downloadedBytes;+ updateState.downloadRate = 0;+ updateState.etaSeconds = 0;updateState.status = 'idle';updateState.message = '安装包已就绪';+ updateDebug('download-cache-hit', { target: path.basename(target), size: updateState.downloadedBytes });return Promise.resolve(target);}log(`[update] 丢弃缓存安装包 ${path.basename(target)}: ${checked.reason}`);@@ -391,31 +512,53 @@ function downloadUpdate() {updateState.message = '正在下载安装包…';return new Promise((resolve, reject) => {const mod = require('https');+ const cleanupTemp = () => { try { fs.unlinkSync(tempTarget); } catch (_) {} };+ let settled = false;+ const failDownload = (error) => {+ if (settled) return;+ settled = true;+ cleanupTemp();+ updateState.status = 'error';+ updateState.error = error && error.message ? error.message : String(error);+ updateState.message = '下载安装包失败';+ const failure = error instanceof Error ? error : new Error(String(error));+ log(`[update] 下载失败 stage=stream target=${path.basename(target)} temp=${path.basename(tempTarget)}: ${failure.message}`);+ updateDebug('download-error', { stage: 'stream', error: failure.message, target: path.basename(target), tempTarget: path.basename(tempTarget) });+ reject(failure);+ };mod.get(updateState.dmgUrl, { headers: { 'User-Agent': 'WorkDaddy/' + DAEMON_VERSION } }, (res) => {- if (res.statusCode >= 400) return reject(new Error('下载失败 HTTP ' + res.statusCode));+ updateDebug('download-response', { statusCode: res.statusCode, contentType: res.headers['content-type'] || null, contentLength: res.headers['content-length'] || null, target: path.basename(target) });+ if (res.statusCode >= 400) return failDownload(new Error('下载失败 HTTP ' + res.statusCode));if ((res.statusCode >= 300) && res.headers.location) {// 跟随重定向(GitHub 资产会 302 到 objects.githubusercontent.com)updateState.dmgUrl = res.headers.location;- resolve(downloadUpdate());+ resolve(downloadUpdateInternal());res.resume();return;}const contentType = String(res.headers['content-type'] || '').toLowerCase();if (!IS_WIN && /text\/html|application\/json/.test(contentType)) {res.resume();- const error = new Error(`下载响应不是 DMG (content-type=${contentType})`);- updateState.status = 'error';- updateState.error = error.message;- reject(error);- return;+ return failDownload(new Error(`下载响应不是 DMG (content-type=${contentType})`));}const total = parseInt(res.headers['content-length'] || '0', 10) || updateState.dmgSize;let received = 0;- const out = fs.createWriteStream(target);+ let lastDebugProgress = -1;+ const startedAt = Date.now();+ updateState.totalBytes = total || 0;+ const out = fs.createWriteStream(tempTarget, { flags: 'wx' });res.on('data', (c) => {received += c.length;+ updateState.downloadedBytes = received;+ const elapsed = Math.max(0.001, (Date.now() - startedAt) / 1000);+ updateState.downloadRate = Math.round(received / elapsed);if (total) {updateState.progress = Math.min(99, Math.round((received / total) * 100));+ updateState.etaSeconds = updateState.downloadRate > 0 ? Math.max(0, Math.ceil((total - received) / updateState.downloadRate)) : null;+ if (updateState.progress >= lastDebugProgress + 10) {+ lastDebugProgress = updateState.progress;+ updateDebug('download-progress', { progress: updateState.progress, downloadedBytes: received, totalBytes: total, downloadRate: updateState.downloadRate, etaSeconds: updateState.etaSeconds });+ }}});res.pipe(out);@@ -423,23 +566,36 @@ function downloadUpdate() {updateState.progress = 100;updateState.status = 'verifying';updateState.message = '校验安装包…';- const expect = parseSha256(updateState.notes);- const checked = validateUpdateArtifact(target, expect);+ const checked = validateUpdateArtifact(tempTarget, expectSha);if (!checked.ok) {- try { fs.unlinkSync(target); } catch (_) {}+ settled = true;+ cleanupTemp();updateState.status = 'error';updateState.error = checked.reason;updateState.message = '安装包校验失败,已删除损坏包';+ log(`[update] 下载失败 stage=verify target=${path.basename(target)} temp=${path.basename(tempTarget)}: ${checked.reason}`);return reject(new Error(checked.reason));}+ try {+ fs.renameSync(tempTarget, target);+ } catch (error) {+ return failDownload(new Error('安装包落盘失败: ' + error.message));+ }+ settled = true;updateState.downloaded = true;updateState.status = 'idle';- updateState.message = '安装包已就绪' + (expect ? '(校验通过)' : '(格式校验通过)');+ updateState.downloadedBytes = checked.size || received;+ updateState.totalBytes = updateState.downloadedBytes;+ updateState.downloadRate = 0;+ updateState.etaSeconds = 0;+ updateState.message = '安装包已就绪(校验通过)';log(`[update] 下载完成 ${target} sha256=${checked.digest}`);+ updateDebug('download-verified', { target: path.basename(target), size: received, sha256: checked.digest });resolve(target);});- out.on('error', (e) => { try { fs.unlinkSync(target); } catch (_) {} reject(e); });- }).on('error', (e) => { try { fs.unlinkSync(target); } catch (_) {} reject(e); });+ out.on('error', failDownload);+ res.on('error', failDownload);+ }).on('error', failDownload);});}@@ -448,6 +604,23 @@ function sha256File(file) {return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');}+function inspectPackagedApp(appDir) {+ const result = { appDir, daemonVersion: null, appVersion: null };+ try {+ const daemonFile = path.join(appDir, 'Contents', 'Resources', 'scripts', 'daemon.js');+ const source = fs.readFileSync(daemonFile, 'utf8');+ const match = source.match(/const DAEMON_VERSION = '([^']+)'/);+ result.daemonVersion = match ? match[1] : null;+ } catch (_) {}+ try {+ const plistFile = path.join(appDir, 'Contents', 'Info.plist');+ const source = fs.readFileSync(plistFile, 'utf8');+ const match = source.match(/<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/);+ result.appVersion = match ? match[1] : null;+ } catch (_) {}+ return result;+}+// 文件存在或没有 Release notes 摘要都不能证明它是可挂载的 DMG:断流、代理错误页// 和旧版残留文件都可能留下普通文件。hdiutil imageinfo 是 macOS UDIF 的确定性预检。function validateUpdateArtifact(file, expectSha = null) {@@ -692,7 +865,7 @@ function extractAppFromDmg(dmgPath) {const appDest = path.join(UPDATE_DIR, appPackageName);return new Promise((resolve, reject) => {const exec = require('child_process').execFile;- const checked = validateUpdateArtifact(dmgPath, parseSha256(updateState.notes));+ const checked = validateUpdateArtifact(dmgPath, expectedUpdateSha256());if (!checked.ok) {log(`[update] DMG 预检失败 ${path.basename(dmgPath)}: ${checked.reason}`);reject(new Error(`DMG 预检失败: ${checked.reason}`));@@ -719,6 +892,11 @@ function extractAppFromDmg(dmgPath) {if (code !== 0 || !fs.existsSync(path.join(appDest, 'Contents', 'Info.plist'))) {return reject(new Error('解包应用失败'));}+ const artifact = inspectPackagedApp(appDest);+ updateDebug('artifact-inspect', { expectedVersion: updateState.latest, daemonVersion: artifact.daemonVersion, appVersion: artifact.appVersion, source: path.basename(dmgPath) });+ if (artifact.daemonVersion && updateState.latest && semverCompare(artifact.daemonVersion, updateState.latest) !== 0) {+ return reject(new Error(`安装包内部 daemon 版本 ${artifact.daemonVersion} 与目标版本 ${updateState.latest} 不一致`));+ }resolve(appDest);});});@@ -731,7 +909,10 @@ function extractAppFromDmg(dmgPath) {// 安装:macOS 调 apply-update.sh(launchctl 停服 → 备份 → 替换 → relaunch);// Windows 调 apply-update.ps1(杀 watchdog/daemon → 释放文件锁 → 替换目录 → 重启)function applyUpdate() {- if (!updateState.downloaded) return Promise.reject(new Error('尚未下载完成'));+ if (!updateState.downloaded) {+ updateDebug('apply-error', { stage: 'preflight', error: '尚未下载完成', latest: updateState.latest });+ return Promise.reject(new Error('尚未下载完成'));+ }updateState.status = 'installing';updateState.message = '正在安装新版本…';updateState.error = null;@@ -745,9 +926,11 @@ function applyUpdate() {startedAt: new Date().toISOString(),pid: process.pid,dataDir: DATA_DIR,+ debugLog: UPDATE_DEBUG_LOG,};updateState.attemptId = attempt.id;writeUpdateAttempt(attempt);+ updateDebug('apply-start', { attemptId: attempt.id, fromVersion: DAEMON_VERSION, targetVersion: updateState.latest, platform: process.platform });const applyLog = path.join(UPDATE_DIR, 'apply.log');const markAttemptFailure = (error, stage = 'update-script') => {attempt.status = stage;@@ -755,6 +938,7 @@ function applyUpdate() {attempt.error = error && error.message ? error.message : String(error);writeUpdateAttempt(attempt);log('[update] 更新尝试失败 stage=' + stage + ': ' + attempt.error);+ updateDebug('apply-error', { stage, attemptId: attempt.id, targetVersion: updateState.latest, error: attempt.error });captureException(error, { stage, extra: { platform: process.platform, attemptId: attempt.id, targetVersion: updateState.latest } }).catch(() => {});};const markSpawnFailure = (error) => markAttemptFailure(error, 'spawn-error');@@ -778,6 +962,7 @@ function applyUpdate() {attempt.targetApp = appDir;writeUpdateAttempt(attempt);log('[update] 执行 apply-update.ps1 attempt=' + attempt.id + ' log=' + applyLog);+ updateDebug('apply-script-start', { script: 'apply-update.ps1', attemptId: attempt.id, sourcePackage: srcZip, targetApp: appDir, applyLog });// 【更新标记】写入 pending.json:watchdog 检测到它在 daemon 退出后【不自动重启 daemon】,// 双重保险(配合本函数末尾「先精确停 watchdog 再自我退出」),彻底杜绝 watchdog 在替换窗口期// 复活 daemon 抢占 47832 端口的竞态(历史上第一轮更新偶发失败、需点第二次才成功的根因)。@@ -810,6 +995,7 @@ function applyUpdate() {attempt.scriptPid = child.pid;writeUpdateAttempt(attempt);log('[update] apply-update.ps1 已启动(经 wscript 中介) pid=' + child.pid);+ updateDebug('apply-script-spawned', { script: 'apply-update.ps1', attemptId: attempt.id, pid: child.pid });});child.unref();// 【竞态加固 · 更新标记】daemon 自我退出后,watchdog 默认会在 3s 后重启新的 daemon 抢占 47832,@@ -840,21 +1026,31 @@ function applyUpdate() {: Promise.reject(new Error('缺少安装包(未找到已下载的 dmg)')));return preUnpack.then((p) => {if (!fs.existsSync(p)) throw new Error('缺少解包后的新应用');+ const artifact = inspectPackagedApp(p);+ updateDebug('artifact-ready', { expectedVersion: updateState.latest, daemonVersion: artifact.daemonVersion, appVersion: artifact.appVersion, source: path.basename(p) });+ if (artifact.daemonVersion && updateState.latest && semverCompare(artifact.daemonVersion, updateState.latest) !== 0) {+ throw new Error(`安装包内部 daemon 版本 ${artifact.daemonVersion} 与目标版本 ${updateState.latest} 不一致`);+ }attempt.sourceApp = p;attempt.targetApp = appPath;writeUpdateAttempt(attempt);log('[update] 执行 apply-update.sh attempt=' + attempt.id + ' src=' + p + ' dst=' + appPath + ' log=' + applyLog);- const child = spawn('bash', [scriptPath, p, appPath, String(ACTUAL_PORT), applyLog, attempt.id], { detached: true, stdio: 'ignore' });+ updateDebug('apply-script-start', { script: 'apply-update.sh', attemptId: attempt.id, sourceApp: p, targetApp: appPath, applyLog });+ const child = spawn('bash', [scriptPath, p, appPath, String(ACTUAL_PORT), applyLog, attempt.id, PROFILE.id], { detached: true, stdio: 'ignore' });child.once('error', markSpawnFailure);child.once('spawn', () => {attempt.status = 'script-started';attempt.scriptPid = child.pid;writeUpdateAttempt(attempt);log('[update] apply-update.sh 已启动 pid=' + child.pid);+ updateDebug('apply-script-spawned', { script: 'apply-update.sh', attemptId: attempt.id, pid: child.pid });});child.unref();return { ok: true, message: '已启动更新,正在替换文件并自动重启,请稍候…' };}).catch((error) => {+ updateState.status = 'error';+ updateState.error = error.message;+ updateState.message = '安装包版本校验失败';if (attempt.status === 'starting') markAttemptFailure(error, 'preflight-error');throw error;});@@ -1833,8 +2029,11 @@ function injectWidget(reason) {// 同步注入当前 daemon 版本号(inject.js 顶部的 __WBS_VERSION__ 占位符会在面板「关于」页直接展示,// 这样版本升级后不需要改 inject.js、面板永远显示 daemon 的真实版本)script = script.replace(/__WBS_VERSION__/g, DAEMON_VERSION);+ // 注入本地 API 能力凭证;旧版面板不会携带该 header,但新版 daemon 会在启动时重新注入新版面板。+ script = script.replace(/__WBS_API_TOKEN__/g, API_TOKEN);script = script.replace(/__WBS_PROFILE__/g, PROFILE.id);script = script.replace(/__WBS_CAPS__/g, JSON.stringify(PROFILE.capabilities));+ updateDebug('inject-version', { reason, injectedVersion: DAEMON_VERSION, profile: PROFILE.id });// 注入策略:不使用 addScriptToEvaluateOnNewDocument(它会在浏览器里持久化注册,// 多次重启会叠加旧版本;旧注册先执行并占住 window.__wbsWidget 守卫,导致新代码被拦截)。// 改为:先用 Runtime.evaluate 暴力清理任何历史残留(不依赖旧版本的 destroy,避免清不干净),@@ -2389,14 +2588,73 @@ function deleteSessionFiles(wbHome, id) {function json(res, code, obj) {const body = JSON.stringify(obj);- res.writeHead(code, {+ const headers = {'Content-Type': 'application/json; charset=utf-8','Content-Length': Buffer.byteLength(body),- 'Access-Control-Allow-Origin': '*',- });+ };+ // 只回显经过来源校验的 Origin;绝不再使用 *,避免恶意网页读取账号/会话响应。+ if (res.__wbsCorsOrigin) {+ headers['Access-Control-Allow-Origin'] = res.__wbsCorsOrigin;+ headers.Vary = 'Origin';+ }+ res.writeHead(code, headers);res.end(body);}+const PUBLIC_API_PATHS = new Set([+ '/api/status',+ '/api/about',+ '/api/about/',+ '/api/update-check',+ '/api/update-status',+]);++function isAllowedApiOrigin(origin) {+ if (!origin) return true; // 本地 CLI/启动器请求没有 Origin+ if (origin === 'null') return true; // Electron file:// renderer+ try {+ const u = new URL(origin);+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return false;+ const host = String(u.hostname || '').toLowerCase();+ // WorkBuddy 的 renderer 可能是官方网页来源,也可能是 loopback DevTools 页面。+ return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' ||+ host === 'workbuddy.cn' || host.endsWith('.workbuddy.cn') ||+ host === 'workbuddy.ai' || host.endsWith('.workbuddy.ai') ||+ host === 'codebuddy.cn' || host.endsWith('.codebuddy.cn') ||+ host === 'codebuddy.ai' || host.endsWith('.codebuddy.ai');+ } catch (_) {+ return false;+ }+}++function hasApiToken(req) {+ const supplied = String(req.headers['x-workdaddy-token'] || '');+ const expected = Buffer.from(API_TOKEN, 'utf8');+ const actual = Buffer.from(supplied, 'utf8');+ return actual.length === expected.length && crypto.timingSafeEqual(actual, expected);+}++function isApiRequestAuthorized(req, p) {+ const origin = String(req.headers.origin || '');+ if (origin && !isAllowedApiOrigin(origin)) return false;+ if (PUBLIC_API_PATHS.has(p)) return true;+ // 保留无 Origin 的手动 launcher/curl 注入和错误面包屑兼容;二者不返回账号数据。+ if (!origin && (p === '/api/inject' || p === '/api/breadcrumb')) return true;+ return hasApiToken(req);+}++function isAllowedDevtoolsOrigin(origin, upstreamPort) {+ if (!origin) return true; // 仅允许无浏览器来源的本地调试客户端+ try {+ const u = new URL(origin);+ const host = String(u.hostname || '').toLowerCase();+ const port = String(u.port || (u.protocol === 'https:' ? 443 : 80));+ return (host === '127.0.0.1' || host === 'localhost' || host === '[::1]') && port === String(upstreamPort);+ } catch (_) {+ return false;+ }+}+function readBody(req) {return new Promise((resolve) => {let data = '';@@ -3594,33 +3852,45 @@ async function fetchCredits(accessToken) {};}-/* ================= 账号导出 / 导入(加密密钥 = workdaddy) =================- * 目的:跨电脑同步账号备份,避免重新登录导致身份过期。- * 说明:用户口吻的「RSA 加密」在本场景用对称加密实现(密钥固定为 workdaddy,任何机器均可解开):- * AES-256-GCM + scryptSync(workdaddy) 派生 32 字节密钥。导出文件的 envelope 仅含元信息,- * 账号内容(含令牌)整体密文,未解密前无法读取。kdf 参数固定,跨机器可还原。+/* ================= 账号导出 / 导入 =================+ * v2 导出:用户在面板输入非空密码;随机 salt + AES-256-GCM,密码不落盘、不写日志。+ * v1 导入:兼容历史固定密码 workdaddy 的导出文件,空密码即走旧格式默认值。*/const EXPORT_PASSPHRASE = 'workdaddy';const EXPORT_KDF_SALT = 'WorkDaddy-account-export-v1';-function exportSecretKey() {- return crypto.scryptSync(EXPORT_PASSPHRASE, EXPORT_KDF_SALT, 32);+function exportSecretKey(password, salt) {+ return crypto.scryptSync(String(password), salt, 32);}// 密文布局:iv(12) + authTag(16) + ciphertext-function encryptExport(plain) {+function encryptExport(plain, password) {+ const salt = crypto.randomBytes(16);const iv = crypto.randomBytes(12);- const cipher = crypto.createCipheriv('aes-256-gcm', exportSecretKey(), iv);+ const cipher = crypto.createCipheriv('aes-256-gcm', exportSecretKey(password, salt), iv);const enc = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);const tag = cipher.getAuthTag();- return Buffer.concat([iv, tag, enc]).toString('base64');+ return { data: Buffer.concat([iv, tag, enc]).toString('base64'), salt: salt.toString('base64') };+}+function decryptExport(b64, password, saltB64) {+ const buf = Buffer.from(String(b64 || ''), 'base64');+ if (buf.length <= 28) throw new Error('导出数据不完整或已损坏');+ const salt = Buffer.from(String(saltB64 || ''), 'base64');+ if (salt.length !== 16) throw new Error('导出文件缺少有效的加密 salt');+ const iv = buf.subarray(0, 12);+ const tag = buf.subarray(12, 28);+ const data = buf.subarray(28);+ const decipher = crypto.createDecipheriv('aes-256-gcm', exportSecretKey(password, salt), iv);+ decipher.setAuthTag(tag);+ return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');}-function decryptExport(b64) {++function decryptLegacyExport(b64, password) {const buf = Buffer.from(String(b64 || ''), 'base64');if (buf.length <= 28) throw new Error('导出数据不完整或已损坏');const iv = buf.subarray(0, 12);const tag = buf.subarray(12, 28);const data = buf.subarray(28);- const decipher = crypto.createDecipheriv('aes-256-gcm', exportSecretKey(), iv);+ const decipher = crypto.createDecipheriv('aes-256-gcm', exportSecretKey(password || EXPORT_PASSPHRASE, EXPORT_KDF_SALT), iv);decipher.setAuthTag(tag);return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8');}@@ -3628,18 +3898,32 @@ function decryptExport(b64) {function handleApi(req, res) {const url = new URL(req.url, `http://${req.headers.host || HOST}`);const p = url.pathname;+ const origin = String(req.headers.origin || '');+ res.__wbsCorsOrigin = origin && isAllowedApiOrigin(origin) ? origin : '';// CORS 预检(注入到 WorkBuddy 页面里的组件需要跨域调用本机 API)if (req.method === 'OPTIONS') {- res.writeHead(204, {- 'Access-Control-Allow-Origin': '*',+ if (origin && !isAllowedApiOrigin(origin)) {+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });+ return res.end('forbidden origin');+ }+ const headers = {'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',- 'Access-Control-Allow-Headers': 'Content-Type',+ 'Access-Control-Allow-Headers': 'Content-Type, X-WorkDaddy-Token','Access-Control-Max-Age': '86400',- });+ };+ if (res.__wbsCorsOrigin) {+ headers['Access-Control-Allow-Origin'] = res.__wbsCorsOrigin;+ headers.Vary = 'Origin';+ }+ res.writeHead(204, headers);return res.end();}+ if (!isApiRequestAuthorized(req, p)) {+ return json(res, 401, { ok: false, error: '本地 API 未授权' });+ }+if (req.method === 'POST' && p === '/api/inject') {return injectWidget('manual').then(() => json(res, 200, { ok: true }),@@ -3788,7 +4072,8 @@ function handleApi(req, res) {}if (req.method === 'GET' && p === '/api/status') {- return json(res, 200, {+ const authenticated = hasApiToken(req);+ const status = {ok: true,version: DAEMON_VERSION,buildId: DAEMON_BUILD_ID,@@ -3796,7 +4081,6 @@ function handleApi(req, res) {cdp: {connected: cdp.connected,port: cdp.port,- targetUrl: cdp.targetUrl,error: cdp.error,},batch: {@@ -3806,10 +4090,14 @@ function handleApi(req, res) {startedAt: batchState.startedAt,last: batchState.last,},- current: currentAccount(),- dataDir: DATA_DIR,- authFile: AUTH_FILE,- });+ };+ if (authenticated) {+ status.cdp.targetUrl = cdp.targetUrl;+ status.current = currentAccount();+ status.dataDir = DATA_DIR;+ status.authFile = AUTH_FILE;+ }+ return json(res, 200, status);}// 诊断:保存一份不含 token 的本地快照,便于用户在异常机器上直接提供文件排查。@@ -3870,39 +4158,47 @@ function handleApi(req, res) {});}- // 导出账号:加密打包全部备份,返回可直接下载的文件内容(密钥 workdaddy)+ // 导出账号:密码必填;v2 使用随机 salt,密码只在本次请求内存在if (req.method === 'POST' && p === '/api/accounts/export') {- try {- const accounts = listAccounts(DATA_DIR);- const items = [];- for (const a of accounts) {- const file = backupPath(DATA_DIR, a.uid);- if (!fs.existsSync(file)) continue;- try {- const raw = fs.readFileSync(file, 'utf8');- JSON.parse(raw); // 跳过损坏备份- items.push({ uid: a.uid, info: raw });- } catch (_) { /* 跳过 */ }+ return readBody(req).then((body) => {+ try {+ const enteredPassword = body && typeof body.password === 'string' ? body.password : '';+ const password = enteredPassword.trim() ? enteredPassword : '';+ if (password.length > 1024) return json(res, 400, { ok: false, error: '密码不能超过 1024 个字符' });+ if (!password.trim()) return json(res, 400, { ok: false, error: '导出密码不能为空' });+ const accounts = listAccounts(DATA_DIR);+ const items = [];+ for (const a of accounts) {+ const file = backupPath(DATA_DIR, a.uid);+ if (!fs.existsSync(file)) continue;+ try {+ const raw = fs.readFileSync(file, 'utf8');+ JSON.parse(raw); // 跳过损坏备份+ items.push({ uid: a.uid, info: raw });+ } catch (_) { /* 跳过 */ }+ }+ if (!items.length) return json(res, 200, { ok: false, error: '没有可导出的账号备份' });+ const payload = { exportType: 'WorkDaddy-accounts', version: 2, accounts: items };+ const encrypted = encryptExport(JSON.stringify(payload), password);+ const envelope = JSON.stringify({+ wbsExport: 'WorkDaddy',+ version: 2,+ createdAt: new Date().toISOString(),+ kdf: 'aes-256-gcm+scrypt',+ salt: encrypted.salt,+ data: encrypted.data,+ });+ const filename = 'WorkDaddy-账号导出-' + new Date().toISOString().slice(0, 10) + '.json';+ log(`[export] 导出 ${items.length} 个账号 -> ${filename}`);+ return json(res, 200, { ok: true, filename, content: envelope, count: items.length });+ } catch (e) {+ log(`[export] 导出失败: ${e.message}`);+ return json(res, 500, { ok: false, error: e.message });}- if (!items.length) return json(res, 200, { ok: false, error: '没有可导出的账号备份' });- const payload = { exportType: 'WorkDaddy-accounts', version: 1, accounts: items };- const envelope = JSON.stringify({- wbsExport: 'WorkDaddy',- version: 1,- createdAt: new Date().toISOString(),- kdf: 'aes-256-gcm+scrypt',- data: encryptExport(JSON.stringify(payload)),- });- const filename = 'WorkDaddy-账号导出-' + new Date().toISOString().slice(0, 10) + '.json';- log(`[export] 导出 ${items.length} 个账号 -> ${filename}`);- return json(res, 200, { ok: true, filename, content: envelope, count: items.length });- } catch (e) {- log(`[export] 导出失败: ${e.message}`);- return json(res, 500, { ok: false, error: e.message });- }+ });}- // 导入账号:从加密文件解密并恢复备份(密钥 workdaddy),按 uid 覆盖写入+ // 导入账号:v2 必须输入密码;历史 v1 文件密码可留空(默认 workdaddy)if (req.method === 'POST' && p === '/api/accounts/import') {return readBody(req).then((body) => {try {@@ -3914,7 +4210,18 @@ function handleApi(req, res) {let envelope;try { envelope = JSON.parse(text); } catch (_) { throw new Error('文件不是有效的导出 JSON'); }if (!envelope || envelope.wbsExport !== 'WorkDaddy') throw new Error('不是 WorkDaddy 的账号导出文件');- const payload = JSON.parse(decryptExport(envelope.data));+ const enteredPassword = body && typeof body.password === 'string' ? body.password : '';+ const password = enteredPassword.trim() ? enteredPassword : '';+ if (password.length > 1024) throw new Error('密码不能超过 1024 个字符');+ let payloadText;+ if (Number(envelope.version) >= 2) {+ if (!envelope.salt) throw new Error('导出文件缺少有效的加密 salt');+ if (!password.trim()) throw new Error('导入该文件需要密码');+ payloadText = decryptExport(envelope.data, password, envelope.salt);+ } else {+ payloadText = decryptLegacyExport(envelope.data, password || EXPORT_PASSPHRASE);+ }+ const payload = JSON.parse(payloadText);const list = Array.isArray(payload && payload.accounts) ? payload.accounts : [];if (!list.length) throw new Error('导入文件中没有账号数据');ensureDirs(DATA_DIR);@@ -3922,7 +4229,9 @@ function handleApi(req, res) {for (const item of list) {const uid = String(item && item.uid || '').trim();const info = item && item.info;- if (!uid || typeof info !== 'string') continue;+ // 导出文件属于用户输入;UID 只能是账号文件名的一段,禁止路径分隔符和+ // 特殊目录名,避免导入请求把认证内容写到 accounts 目录之外。+ if (!uid || uid.length > 200 || uid === '.' || uid === '..' || /[\\/\0]/.test(uid) || typeof info !== 'string') continue;let j;try { j = JSON.parse(info); } catch (_) { continue; }const acct = j.account || (Array.isArray(j.accounts) && j.accounts[0]);@@ -4541,7 +4850,8 @@ function handleApi(req, res) {let build = { version: DAEMON_VERSION, commit: null, buildAt: null };try {const pjson = require('./package.json');- build.version = pjson.version || DAEMON_VERSION;+ // package.json 可能随 app 壳滞后于 daemon.js;关于页和升级结果必须展示实际运行代码版本。+ build.packageVersion = pjson.version || null;build.commit = process.env.WBSWITCH_GIT_COMMIT || null;build.buildAt = process.env.WBSWITCH_BUILD_AT || null;} catch (_) { /* 没有 package.json 时退回到 DAEMON_VERSION */ }@@ -4559,11 +4869,12 @@ function handleApi(req, res) {if (m) appVersion = m[1];}} catch (_) { /* 解析失败忽略 */ }+ updateDebug('about-version', { daemonVersion: DAEMON_VERSION, packageVersion: build.packageVersion || null, appVersion, shownVersion: DAEMON_VERSION });return json(res, 200, {ok: true,name: WORKDADDY_INSTALL_NAME,tagline: PROFILE.name + ' 的多账号 · 主题 · 增强工具集',- version: build.version,+ version: DAEMON_VERSION,appVersion: appVersion,license: 'AGPL-3.0',repository: 'https://github.com/babygoton/WorkDaddy',@@ -4587,6 +4898,7 @@ function handleApi(req, res) {hasUpdate: st.hasUpdate,dmgUrl: st.dmgUrl,dmgSize: st.dmgSize,+ assetName: st.assetName,notes: st.notes,message: st.message,error: st.error || null,@@ -4595,8 +4907,12 @@ function handleApi(req, res) {);}if (req.method === 'GET' && p === '/api/update-status') {- return json(res, 200, {+ const status = {ok: true,+ // 前端在 daemon 重启后通过版本变化结束等待;缺少该字段会永久停留在“重启中”。+ version: DAEMON_VERSION,+ daemonVersion: DAEMON_VERSION,+ buildId: DAEMON_BUILD_ID,status: updateState.status,progress: updateState.progress,message: updateState.message,@@ -4604,24 +4920,46 @@ function handleApi(req, res) {latest: updateState.latest,hasUpdate: updateState.hasUpdate,downloaded: updateState.downloaded,+ downloadedBytes: updateState.downloadedBytes,+ totalBytes: updateState.totalBytes,+ downloadRate: updateState.downloadRate,+ etaSeconds: updateState.etaSeconds,attemptId: updateState.attemptId,- applyLog: path.join(UPDATE_DIR, 'apply.log'),- });+ };+ if (hasApiToken(req)) {+ status.applyLog = path.join(UPDATE_DIR, 'apply.log');+ status.debugLog = UPDATE_DEBUG_LOG;+ }+ return json(res, 200, status);}if (req.method === 'POST' && p === '/api/update-download') {updateState.error = null;- return downloadUpdate()- .then((file) => json(res, 200, { ok: true, file, size: fs.existsSync(file) ? fs.statSync(file).size : 0 }))- .catch((e) => {- updateState.error = e.message;- updateState.message = '下载失败';- return json(res, 200, { ok: false, error: e.message });- });+ downloadUpdate().then(() => {+ log('[update] 后台下载任务完成');+ }).catch((e) => {+ updateState.error = e.message;+ updateState.message = '下载失败';+ });+ return json(res, 202, {+ ok: true,+ started: true,+ status: updateState.status,+ progress: updateState.progress,+ downloadedBytes: updateState.downloadedBytes,+ totalBytes: updateState.totalBytes,+ });}if (req.method === 'POST' && p === '/api/update-apply') {return applyUpdate()- .then((r) => json(res, 200, { ...r, attemptId: updateState.attemptId, applyLog: path.join(UPDATE_DIR, 'apply.log') }))- .catch((e) => json(res, 200, { ok: false, error: e.message }));+ .then((r) => json(res, 200, { ...r, attemptId: updateState.attemptId, applyLog: path.join(UPDATE_DIR, 'apply.log'), debugLog: UPDATE_DEBUG_LOG }))+ .catch((e) => json(res, 200, {+ ok: false,+ error: e.message,+ status: updateState.status,+ attemptId: updateState.attemptId,+ applyLog: path.join(UPDATE_DIR, 'apply.log'),+ debugLog: UPDATE_DEBUG_LOG,+ }));}// 暂存卡死诊断:注入脚本上报的面包屑/错误栈,仅写 daemon 日志(崩溃排查用)@@ -5003,8 +5341,8 @@ function startServer() {res.end('not found');});- // DevTools WebSocket 代理:/devtools-proxy/<targetId> —— 浏览器前端连 daemon(不校验 Origin),- // daemon 用无 Origin 的 WebSocket 连当前 CDP 端口转发(Electron CDP 拒绝带 Origin 的连接)+ // DevTools WebSocket 代理:只接受当前 CDP DevTools 页面来源,拒绝任意网页借代理控制 renderer。+ // daemon 到 Electron CDP 的上游连接仍去掉 Origin(Electron CDP 会拒绝带 Origin 的连接)。if (wsLib) {const { WebSocketServer } = wsLib;const wss = new WebSocketServer({ noServer: true });@@ -5013,10 +5351,15 @@ function startServer() {try { pathname = new URL(req.url, 'http://x').pathname; } catch (_) { socket.destroy(); return; }const m = /^\/devtools-proxy\/([A-Za-z0-9]+)$/.exec(pathname);if (!m) { socket.destroy(); return; }+ // 与 /api/devtools-url 使用同一套回退顺序:CDP 尚未完成内存连接时,+ // 仍允许已持久化端口上的官方 DevTools 页面建立代理连接。+ const upstreamPort = cdp.port || readCdpPortFile() || CDP_PORT_HINT || 9222;+ if (!upstreamPort || !isAllowedDevtoolsOrigin(String(req.headers.origin || ''), upstreamPort)) {+ socket.destroy();+ return;+ }wss.handleUpgrade(req, socket, head, (front) => {if (!WebSocketCtor) { try { front.close(); } catch (_) {} return; }- const upstreamPort = cdp.port;- if (!upstreamPort) { try { front.close(); } catch (_) {} return; }const back = new WebSocketCtor('ws://127.0.0.1:' + upstreamPort + '/devtools/page/' + m[1]);let backReady = false;let keepAlive = null;@@ -5119,6 +5462,7 @@ refreshAskModeIfEnabled();log('WorkBuddy 多账号切换器启动 (CDP 模式)');log(`登录信息文件: ${AUTH_FILE}`);log(`备份目录: ${DATA_DIR}`);+updateDebug('daemon-start', { authFile: AUTH_FILE, dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });restoreSleepMode();startServer();diff --git a/scripts/inject.js b/scripts/inject.jsindex 1b05185..e50b47b 100644--- a/scripts/inject.js+++ b/scripts/inject.js@@ -78,6 +78,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var API = '__WBS_API__';var PROFILE_ID = '__WBS_PROFILE__';var CAPS = __WBS_CAPS__;+ var WBS_API_TOKEN = '__WBS_API_TOKEN__';// 面板品牌名跟随 profile:workbuddy-ai 显示 WorkDaddy AI,其余显示 WorkDaddyvar WBS_BRAND = PROFILE_ID === 'workbuddy-ai' ? 'WorkDaddy AI' : 'WorkDaddy';@@ -97,7 +98,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {var line = '[wbscrash] ' + kind + ': ' + msg + (stack ? '\n' + stack : '');try { console.error(line); } catch (_) {}try {- fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ msg: 'crash:' + kind + ':' + msg, extra: { stack: (stack || '').slice(0, 1500) } }) }).catch(function () {});+ fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json', 'X-WorkDaddy-Token': WBS_API_TOKEN }, body: JSON.stringify({ msg: 'crash:' + kind + ':' + msg, extra: { stack: (stack || '').slice(0, 1500) } }) }).catch(function () {});} catch (_) {}}window.addEventListener('error', function (ev) { wbsReportErr('error', ev); });@@ -233,9 +234,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}function api(path, opts) {- return fetch(API + path, opts).then(function (r) {+ opts = opts || {};+ var request = {};+ Object.keys(opts).forEach(function (key) { request[key] = opts[key]; });+ var headers = {};+ if (opts.headers) {+ Object.keys(opts.headers).forEach(function (key) { headers[key] = opts.headers[key]; });+ }+ headers['X-WorkDaddy-Token'] = WBS_API_TOKEN;+ request.headers = headers;+ return fetch(API + path, request).then(function (r) {return r.json().then(function (j) {- if (!r.ok || j.ok === false) throw new Error(j.error || '请求失败');+ if (!r.ok || j.ok === false) {+ var error = new Error(j.error || '请求失败');+ error.payload = j;+ throw error;+ }return j;});});@@ -1449,7 +1463,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {function crumb(msg) {try { console.log('[wbscrum]', msg); } catch (e) {}try {- fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ msg: msg }) }).catch(function () {});+ fetch(API + '/api/breadcrumb', { method: 'POST', headers: { 'content-type': 'application/json', 'X-WorkDaddy-Token': WBS_API_TOKEN }, body: JSON.stringify({ msg: msg }) }).catch(function () {});} catch (e) {}}listen(stashBtn, 'click', function () {@@ -1573,8 +1587,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-acct-stat"><span>总积分</span><strong id="wbs-acct-total">-</strong></div>' +'</div>' +'<div class="wbs-acct-actions">' +- '<button class="wbs-acct-io" type="button" data-act="export" title="把全部账号备份加密导出为文件(密钥 workdaddy),可拷贝到其他电脑导入">' + EXPORT_ICON + '<span>导出</span></button>' +- '<button class="wbs-acct-io" type="button" data-act="import" title="从加密导出文件导入账号备份(密钥 workdaddy)">' + IMPORT_ICON + '<span>导入</span></button>' ++ '<button class="wbs-acct-io" type="button" data-act="export" title="输入密码后导出全部账号备份">' + EXPORT_ICON + '<span>导出</span></button>' ++ '<button class="wbs-acct-io" type="button" data-act="import" title="从加密导出文件导入账号备份">' + IMPORT_ICON + '<span>导入</span></button>' +'</div>' +'</div>' +'<div class="wbs-acct-list"></div>' +@@ -1588,40 +1602,95 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {root.querySelector('#wbs-import-file').addEventListener('change', onImportFile);}- // 导出账号:请求 daemon 加密打包,触发浏览器下载+ function closeAccountPasswordModal(mask) {+ if (mask && mask.parentNode) mask.parentNode.removeChild(mask);+ }++ function openAccountPasswordModal(mode, onConfirm) {+ closeAccountPasswordModal(panel && panel.querySelector('#wbs-account-password-modal'));+ var isExport = mode === 'export';+ var mask = document.createElement('div');+ mask.className = 'wbs-panel-modal-mask';+ mask.id = 'wbs-account-password-modal';+ mask.innerHTML =+ '<div class="wbs-password-modal" role="dialog" aria-modal="true" aria-labelledby="wbs-password-title">' ++ '<div class="wbs-login-modal-title" id="wbs-password-title">' + (isExport ? '导出账号' : '导入账号') + '</div>' ++ '<label class="wbs-password-field"><span>密码' + (isExport ? '' : '(可留空)') + '</span>' ++ '<input id="wbs-account-password" type="password" autocomplete="new-password" placeholder="' + (isExport ? '请输入密码' : '新版文件请输入密码') + '"></label>' ++ '<div class="wbs-password-hint">' + (isExport ? '密码不能为空,请妥善保管。' : '导入密码可留空;旧版导出文件默认使用 workdaddy。') + '</div>' ++ '<div class="wbs-password-error" id="wbs-password-error" role="alert"></div>' ++ '<div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" id="wbs-password-cancel">取消</button>' ++ '<button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-password-confirm">确定</button></div>' ++ '</div>';+ (panel || root).appendChild(mask);+ var input = mask.querySelector('#wbs-account-password');+ var error = mask.querySelector('#wbs-password-error');+ var confirm = mask.querySelector('#wbs-password-confirm');+ var close = function () { closeAccountPasswordModal(mask); };+ mask.querySelector('#wbs-password-cancel').addEventListener('click', close);+ mask.addEventListener('click', function (ev) { if (ev.target === mask) close(); });+ confirm.addEventListener('click', function () {+ var value = input.value;+ if (isExport && !value.trim()) {+ error.textContent = '密码不能为空';+ input.focus();+ return;+ }+ confirm.disabled = true;+ confirm.textContent = '处理中…';+ close();+ onConfirm(value);+ });+ input.addEventListener('keydown', function (ev) {+ if (ev.key === 'Enter') confirm.click();+ if (ev.key === 'Escape') close();+ });+ setBuildTimeout(function () { input.focus(); }, 0);+ }++ // 导出账号:密码必填,daemon 使用随机 salt 加密后触发浏览器下载。function onExportAccounts() {- api('/api/accounts/export', { method: 'POST' })- .then(function (r) {- var blob = new Blob([r.content], { type: 'application/json' });- var url = URL.createObjectURL(blob);- var a = document.createElement('a');- a.href = url;- a.download = r.filename || 'WorkDaddy-accounts.json';- document.body.appendChild(a);- a.click();- setTimeout(function () { document.body.removeChild(a); URL.revokeObjectURL(url); }, 300);- toast('已导出 ' + r.count + ' 个账号(已加密,需用密钥 workdaddy 在其他电脑导入)', false, root);+ openAccountPasswordModal('export', function (password) {+ api('/api/accounts/export', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ password: password }),})- .catch(function (e) { toast('导出失败: ' + e.message, true, root); });+ .then(function (r) {+ var blob = new Blob([r.content], { type: 'application/json' });+ var url = URL.createObjectURL(blob);+ var a = document.createElement('a');+ a.href = url;+ a.download = r.filename || 'WorkDaddy-accounts.json';+ document.body.appendChild(a);+ a.click();+ setTimeout(function () { document.body.removeChild(a); URL.revokeObjectURL(url); }, 300);+ toast('已导出 ' + r.count + ' 个账号(已加密)', false, root);+ })+ .catch(function (e) { toast('导出失败: ' + e.message, true, root); });+ });}- // 导入账号:读所选文件内容 → daemon 解密 → 恢复备份 → 刷新列表+ // 导入账号:读文件后输入密码;空密码仅对历史 workdaddy 格式有效。function onImportFile(ev) {var file = ev.target && ev.target.files && ev.target.files[0];ev.target.value = '';if (!file) return;var reader = new FileReader();reader.onload = function () {- api('/api/accounts/import', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ content: String(reader.result) }),- })- .then(function (r) {- toast('成功导入 ' + r.count + ' 个账号', false, root);- refresh();+ var content = String(reader.result);+ openAccountPasswordModal('import', function (password) {+ api('/api/accounts/import', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ content: content, password: password }),})- .catch(function (e) { toast('导入失败: ' + e.message, true, root); });+ .then(function (r) {+ toast('成功导入 ' + r.count + ' 个账号', false, root);+ refresh();+ })+ .catch(function (e) { toast('导入失败: ' + e.message, true, root); });+ });};reader.onerror = function () { toast('读取文件失败', true, root); };reader.readAsText(file);@@ -2627,8 +2696,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'<div class="wbs-update-notes" id="wbs-update-notes"></div>' +'<div class="wbs-update-actions">' +'<button class="wbs-update-btn" id="wbs-update-btn" type="button">立即更新</button>' +- '<span class="wbs-update-progress" id="wbs-update-progress" style="display:none"></span>' +'</div>' ++ '<div class="wbs-update-progress" id="wbs-update-progress" style="display:none" role="status" aria-live="polite"></div>' +'<div class="wbs-update-bar" id="wbs-update-bar" style="display:none;height:6px;border-radius:3px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 22%,transparent);overflow:hidden;margin-top:8px"><i id="wbs-update-bar-fill" style="display:block;height:100%;width:0;border-radius:3px;background:var(--wb-button-primary-bg,#1f1f1f);transition:width .6s ease"></i></div>' +'</div>' +'<div class="wbs-pcard wbs-about-hero">' +@@ -2664,7 +2733,9 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {el = aboutPane.querySelector('#wbs-about-badge');if (el && d.principle) el.textContent = d.principle;el = aboutPane.querySelector('#wbs-about-ver');- if (el && d.version) el.textContent = 'v' + d.version;+ // 运行中的 daemon 注入版本是第一事实来源;旧 app 壳里的 package.json 可能滞后。+ var runtimeVersion = WBS_VERSION && WBS_VERSION.indexOf('__WBS_') !== 0 ? WBS_VERSION : d.version;+ if (el && runtimeVersion) el.textContent = 'v' + runtimeVersion;var repo = aboutPane.querySelector('#wbs-about-repo');if (repo && d.repository) repo.href = d.repository;var issues = aboutPane.querySelector('#wbs-about-issues');@@ -2688,7 +2759,14 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (title) title.textContent = '发现新版本 v' + d.latest;var notes = aboutPane.querySelector('#wbs-update-notes');if (notes) {- notes.textContent = (d.notes || '').split('\n').filter(function (l) { return l.trim() && !/^SHA-?256[::]/i.test(l); }).slice(0, 6).join('\n') || '有新版本可用,点击立即更新。';+ var noteLines = (d.notes || '').split('\n').map(function (l) {+ return l.trim().replace(/^[-*+]\s*/, '').replace(/^#+\s*/, '');+ }).filter(function (l) {+ return l && !/^SHA-?256[::]/i.test(l) && !/^https?:\/\//i.test(l) && !/full changelog/i.test(l);+ }).slice(0, 3).map(function (l) {+ return l.length > 48 ? l.slice(0, 47) + '…' : l;+ });+ notes.textContent = noteLines.join('\n') || '有新版本可用,点击更新。';}var btn = aboutPane.querySelector('#wbs-update-btn');if (btn) {@@ -2697,7 +2775,51 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}).catch(function () {});}- // 点击「立即更新」:下载 → 轮询状态 → 安装(daemon 写脚本替换 + 自动重启)+ function updateLogTimestamp() {+ var d = new Date();+ var pad = function (n) { return String(n).padStart(2, '0'); };+ return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());+ }+ function appendUpdateLog(prog, message) {+ if (!prog || !message) return;+ var text = String(message);+ if (prog._wbsLastLog === text) return;+ prog._wbsLastLog = text;+ prog.style.display = '';+ var line = document.createElement('div');+ line.className = 'wbs-update-log-line';+ line.textContent = updateLogTimestamp() + ' ' + text;+ prog.appendChild(line);+ while (prog.childNodes.length > 80) prog.removeChild(prog.firstChild);+ prog.scrollTop = prog.scrollHeight;+ }+ function formatDownloadRate(rate) {+ var n = Number(rate) || 0;+ if (n < 1024) return Math.round(n) + ' B/s';+ if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB/s';+ return (n / (1024 * 1024)).toFixed(1) + ' MB/s';+ }+ function formatDownloadEta(seconds) {+ if (seconds === null || typeof seconds === 'undefined' || !isFinite(Number(seconds))) return '剩余时间计算中';+ var s = Math.max(0, Math.round(Number(seconds)));+ if (s < 60) return '预计剩余 ' + s + ' 秒';+ var m = Math.floor(s / 60);+ var rem = s % 60;+ return '预计剩余 ' + m + ' 分 ' + rem + ' 秒';+ }+ function formatUpdateFailure(value, fallback) {+ var payload = value && value.payload ? value.payload : (value && typeof value === 'object' ? value : null);+ var detail = payload && (payload.error || payload.message) || (value && value.message) || fallback || '未知错误';+ var stage = payload && payload.status;+ var stageNames = { checking: '检查', downloading: '下载', verifying: '校验', installing: '安装', rebooting: '重启' };+ var text = '更新失败' + (stage ? '(阶段:' + (stageNames[stage] || stage) + ')' : '') + ':' + detail;+ if (payload && payload.attemptId) text += ';尝试 ID:' + payload.attemptId;+ if (payload && payload.applyLog) text += ';安装日志:' + payload.applyLog;+ if (payload && payload.debugLog) text += ';诊断日志:' + payload.debugLog;+ return text;+ }++ // 点击「立即更新」:后台下载 → 轮询状态 → 安装(daemon 写脚本替换 + 自动重启)function startUpdate() {var btn = aboutPane.querySelector('#wbs-update-btn');var prog = aboutPane.querySelector('#wbs-update-progress');@@ -2705,14 +2827,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {if (!btn || !card) return;btn.disabled = true;btn.textContent = '更新中…';- if (prog) { prog.style.display = ''; prog.textContent = '正在准备更新…'; }+ if (prog) { prog.innerHTML = ''; prog._wbsLastLog = ''; appendUpdateLog(prog, '正在准备更新…'); }api('/api/update-download', { method: 'POST' }).then(function (d) {if (!d.ok) throw new Error(d.error || '下载失败');return pollUpdateProgress(prog, btn, card);}).catch(function (e) {if (btn) { btn.disabled = false; btn.textContent = '重试更新'; }- if (prog) prog.textContent = (e && e.message) || '更新失败';- try { toast('更新失败: ' + ((e && e.message) || e), true, root); } catch (_) {}+ var failure = formatUpdateFailure(e, '更新失败');+ if (prog) appendUpdateLog(prog, failure);+ try { toast(failure, true, root); } catch (_) {}});}@@ -2722,27 +2845,29 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {// 重启等待阶段的分阶段预估进度(替换/启动真实耗时不透明,按安装向导惯例分步推进,// 让用户看到进度而非一句「30~60 秒」干等;新 daemon 真正就绪后以实际版本收尾)var REBOOT_STEPS = [- { t: 0, pct: 12, text: '正在停止旧版服务…' },- { t: 3000, pct: 30, text: '正在写入新版本文件…' },- { t: 9000, pct: 55, text: '正在启动新版本…' },- { t: 16000, pct: 80, text: '正在连接新服务…' },- { t: 26000, pct: 95, text: '快完成了,请稍候…' },+ { t: 0, pct: 12, text: '停止旧服务…' },+ { t: 3000, pct: 30, text: '写入新文件…' },+ { t: 9000, pct: 55, text: '启动新版本…' },+ { t: 16000, pct: 80, text: '连接新服务…' },+ { t: 26000, pct: 95, text: '即将完成…' },];function pollUpdateProgress(prog, btn, card) {return new Promise(function (resolve, reject) {var rounds = 0;var rebooting = false;var rebootElapsed = 0;+ var applyStarted = false;+ var lastStatus = null;var bar = card ? card.querySelector('#wbs-update-bar') : null;var barFill = bar ? bar.querySelector('#wbs-update-bar-fill') : null;function renderRebootUi() {- var text = WBS_BRAND + ' 正在重启,更新即将完成,请稍候…';+ var text = '正在重启…';var pct = 95;for (var i = 0; i < REBOOT_STEPS.length; i++) {if (rebootElapsed >= REBOOT_STEPS[i].t) { text = REBOOT_STEPS[i].text; pct = REBOOT_STEPS[i].pct; }}- if (rebootElapsed > 45000) { text = '启动较慢,请耐心等待…(也可双击桌面 ' + WBS_BRAND + ' 图标手动启动)'; pct = 99; }- if (prog) prog.textContent = text;+ if (rebootElapsed > 45000) { text = '启动较慢,请稍候…'; pct = 99; }+ appendUpdateLog(prog, text);if (bar) bar.style.display = '';if (barFill) barFill.style.width = pct + '%';}@@ -2751,14 +2876,22 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {api('/api/update-status').then(function (s) {if (!prog) return;if (!s) throw new Error('status-empty');+ lastStatus = s;if (rebooting) {+ if (rebootElapsed > 120000) {+ clearInterval(timer);+ var timeoutError = new Error('新版本服务在 120 秒内未恢复');+ timeoutError.payload = lastStatus || {};+ reject(timeoutError);+ return;+ }// 重启等待阶段:新 daemon 已就绪且有版本 → 完成var newVer = s.version;if (newVer && (!WBS_VERSION || WBS_VERSION.indexOf('__WBS_') === 0 || newVer !== WBS_VERSION)) {clearInterval(timer);if (bar) bar.style.display = '';if (barFill) barFill.style.width = '100%';- prog.textContent = '✅ 已升级到 v' + newVer + ',更新完成';+ appendUpdateLog(prog, '已升级到 v' + newVer + ',更新完成');if (btn) btn.textContent = '已完成';resolve(true);} else {@@ -2769,36 +2902,43 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {}var st = s.status;if (st === 'downloading' || st === 'verifying') {- prog.textContent = s.message + (s.progress ? ' ' + s.progress + '%' : '');+ var transfer = '';+ if (st === 'downloading') {+ transfer = ' · ' + formatDownloadRate(s.downloadRate) + ' · ' + formatDownloadEta(s.etaSeconds);+ }+ appendUpdateLog(prog, (s.message || '正在下载…') + (s.progress ? ' ' + s.progress + '%' : '') + transfer);} else if (st === 'installing') {- prog.textContent = '正在安装新版本…';+ appendUpdateLog(prog, '正在安装新版本…');if (btn) btn.textContent = '安装中…';fireApply();} else if (st === 'error') {clearInterval(timer);- reject(new Error(s.error || s.message || '更新出错'));+ var statusError = new Error(formatUpdateFailure(s, '更新出错'));+ statusError.payload = s;+ reject(statusError);} else if (st === 'idle' && s.downloaded) {- prog.textContent = '下载完成,准备安装…';+ appendUpdateLog(prog, '下载完成,准备安装…');fireApply();} else if (st === 'idle' && s.hasUpdate) {- prog.textContent = s.message || '发现新版本,准备更新…';+ appendUpdateLog(prog, s.message || '发现新版本,准备更新…');}}).catch(function (e) {// 连接断开(daemon 已退出替换文件)= 正在重启;稍等片刻再进入等待态- if (!rebooting && rounds > 2) { enterRebootWait(); return; }+ if (!rebooting && rounds > 2) { appendUpdateLog(prog, '更新服务正在重启…'); enterRebootWait(); return; }if (rebooting) { rebootElapsed += 1000; renderRebootUi(); return; }- clearInterval(timer); reject(new Error((e && e.message) || '更新失败'));+ clearInterval(timer); reject(new Error(formatUpdateFailure(e, '更新失败')));});function fireApply() {- if (rebooting) return;+ if (rebooting || applyStarted) return;+ applyStarted = true;api('/api/update-apply', { method: 'POST' }).then(function (r) {if (r && r.ok) { enterRebootWait(); }- else { clearInterval(timer); reject(new Error((r && r.error) || '安装失败')); }+ else { clearInterval(timer); reject(new Error(formatUpdateFailure(r, '安装失败'))); }}).catch(function (e2) {var msg = String((e2 && e2.message) || e2);if (/ECONNREFUSED|Failed to fetch|NetworkError|load failed/i.test(msg)) { enterRebootWait(); }- else { clearInterval(timer); reject(new Error((e2 && e2.message) || '安装失败')); }+ else { clearInterval(timer); reject(new Error(formatUpdateFailure(e2, '安装失败'))); }});}@@ -4996,11 +5136,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-update-dot{width:8px;height:8px;border-radius:50%;background:#e24b4a;flex-shrink:0}','.wbs-update-title{font-size:13px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f)}','.wbs-update-notes{font-size:11.5px;line-height:1.6;color:var(--wb-icon-tertiary,#777);white-space:pre-line;max-height:72px;overflow:hidden;margin-bottom:10px}',- '.wbs-update-actions{display:flex;align-items:center;gap:10px}',- '.wbs-update-btn{font-size:12px;font-weight:600;color:var(--wb-button-primary-fg,#fff);background:var(--wb-button-primary-bg,#1f1f1f);border:none;padding:6px 16px;border-radius:8px;cursor:pointer;transition:opacity .15s}',+ '.wbs-update-actions{display:flex;align-items:center;gap:10px;min-width:0}',+ '.wbs-update-btn{font-size:12px;font-weight:600;color:var(--wb-button-primary-fg,#fff);background:var(--wb-button-primary-bg,#1f1f1f);border:none;padding:6px 10px;border-radius:8px;cursor:pointer;transition:opacity .15s;flex:0 0 112px;min-width:112px;box-sizing:border-box;white-space:nowrap}','.wbs-update-btn:hover{opacity:.85}','.wbs-update-btn:disabled{opacity:.5;cursor:default}',- '.wbs-update-progress{font-size:11.5px;color:var(--wb-icon-tertiary,#888)}',+ '.wbs-update-progress{display:block;box-sizing:border-box;margin-top:8px;max-height:126px;overflow-y:auto;padding:7px 8px;border:1px solid rgba(226,75,74,.2);border-radius:8px;background:rgba(226,75,74,.045);font-size:10.5px;color:var(--wb-icon-tertiary,#888);line-height:1.5;overflow-wrap:anywhere;scrollbar-width:thin}',+ '.wbs-update-log-line{white-space:normal;word-break:break-word;padding:1px 0}',/* 官方壁纸网格 */'.wbs-wallpapers{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}','.wbs-wp{border-radius:10px;overflow:hidden;cursor:pointer;border:2px solid transparent;transition:all .15s;position:relative}',@@ -5064,6 +5205,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {'.wbs-panel-modal-mask{position:absolute;inset:0;z-index:20;display:flex;align-items:center;justify-content:center;padding:14px;background:transparent;pointer-events:auto;animation:wbs-modal-in .16s ease}','.wbs-login-modal{width:min(360px,calc(100% - 28px));box-sizing:border-box;padding:16px;border:1px solid var(--wb-border-default,rgba(0,0,0,.12));border-radius:14px;background:var(--wb-bg-popover,#fff);box-shadow:0 10px 40px rgba(0,0,0,.25)}','.wbs-login-modal-title{font-size:15px;font-weight:700;line-height:1.35;color:var(--wb-color-text-primary,#1f1f1f);margin:0 0 14px}',+ '.wbs-password-modal{width:min(360px,calc(100% - 28px));box-sizing:border-box;padding:16px;border:1px solid var(--wb-border-default,rgba(0,0,0,.12));border-radius:14px;background:var(--wb-bg-popover,#fff);box-shadow:0 10px 40px rgba(0,0,0,.25)}',+ '.wbs-password-field{display:flex;flex-direction:column;gap:6px;font-size:12px;color:var(--wb-icon-secondary,#666)}',+ '.wbs-password-field input{box-sizing:border-box;width:100%;min-height:34px;padding:7px 9px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:8px;background:var(--wb-bg-secondary,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;outline:none}',+ '.wbs-password-field input:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 16%,transparent)}',+ '.wbs-password-hint{margin-top:7px;color:var(--wb-icon-tertiary,#999);font-size:11px;line-height:1.5}',+ '.wbs-password-error{min-height:17px;margin-top:4px;color:#d14343;font-size:11px;line-height:1.5}','.wbs-login-body{display:flex;flex-direction:column;gap:9px;margin-bottom:16px}','.wbs-login-option{display:flex;align-items:flex-start;gap:10px;width:100%;box-sizing:border-box;padding:12px 13px;border:1px solid transparent;border-radius:11px;background:var(--wb-bg-popover,#fff);cursor:pointer;text-align:left;transition:border-color .16s,background .16s,box-shadow .16s;font-family:inherit}','.wbs-login-option:hover{border-color:var(--wb-border-strong,#b9b9bd);background:var(--wb-bg-hover,#f5f5f5)}',diff --git a/test/update-layout.test.js b/test/update-layout.test.jsindex fdece4d..71dcc86 100644--- a/test/update-layout.test.js+++ b/test/update-layout.test.js@@ -17,6 +17,34 @@ test('Windows updater launches the installed scripts launcher', () => {assert.match(script, /Invoke-RestMethod[\s\S]*\/api\/status/);});+test('update status exposes the running daemon version so reboot polling can finish', () => {+ const daemon = read('daemon.js');+ const statusStart = daemon.indexOf("p === '/api/update-status'");+ const statusEnd = daemon.indexOf("p === '/api/update-download'", statusStart);+ assert.ok(statusStart >= 0 && statusEnd > statusStart);+ const statusBlock = daemon.slice(statusStart, statusEnd);+ assert.match(statusBlock, /version:\s*DAEMON_VERSION/);+});++test('update download starts asynchronously and reports transfer telemetry', () => {+ const daemon = read('daemon.js');+ const routeStart = daemon.indexOf("p === '/api/update-download'");+ const routeEnd = daemon.indexOf("p === '/api/update-apply'", routeStart);+ const statusStart = daemon.indexOf("p === '/api/update-status'");+ const statusEnd = daemon.indexOf("p === '/api/update-download'", statusStart);+ const statusBlock = daemon.slice(statusStart, statusEnd);+ assert.ok(routeStart >= 0 && routeEnd > routeStart);+ const route = daemon.slice(routeStart, routeEnd);+ assert.match(route, /downloadUpdate\(\)\.then/);+ assert.match(route, /return json\(res, 202/);+ assert.match(daemon, /downloadRate/);+ assert.match(daemon, /etaSeconds/);+ assert.match(daemon, /downloadedBytes/);+ assert.match(daemon, /totalBytes/);+ assert.match(statusBlock, /downloadRate/);+ assert.match(statusBlock, /etaSeconds/);+});+test('Windows updater stops the watchdog before waiting for the API port', () => {const script = read('apply-update.ps1');const stop = script.indexOf('function Stop-WatchdogAndPort');@@ -42,11 +70,14 @@ test('Windows install and update release a locked launcher before replacing it',test('macOS updater stops the daemon before waiting for the API port', () => {const script = read('apply-update.sh');- const stop = script.indexOf('pkill -f');+ const stop = script.indexOf('stop_daemons');const wait = script.indexOf('for i in $(seq 1 30)');assert.notEqual(stop, -1);assert.notEqual(wait, -1);assert.ok(stop < wait, 'daemon shutdown must precede the port wait');+ assert.match(script, /PROFILE="\$\{6:-workbuddy-cn\}"/);+ assert.match(script, /lsof -nP -ti tcp:/);+ assert.match(script, /kill -TERM/);});test('updaters fail loudly and leave a durable attempt trail', () => {@@ -173,6 +204,8 @@ test('release scripts package only WorkDaddy and WorkDaddy AI', () => {assert.match(win, /WorkDaddy AI\.lnk|PACKAGE_NAME="WorkDaddy AI"/);assert.match(win, /OUT="release\/windows\/WorkDaddy/);assert.match(mac, /PACKAGE_APP_NAME="WorkDaddy AI"/);+ assert.match(mac, /Contents\/Resources\/scripts\/daemon\.js/);+ assert.match(win, /BUILD_VERSION="\$VERSION"/);assert.match(installer, /\$lnkPath\s*=\s*Join-Path\s+\$desktopDir\s+\(\$productName\s+\+\s+'\.lnk'\)/);});@@ -325,6 +358,109 @@ test('daemon and Windows launcher logs identify the active WorkBuddy client', ()assert.match(read('win-launcher.js'), /\[client=\$\{PROFILE\.name\}\] \[profile=\$\{PROFILE\.id\}\]/);});+test('update card keeps the action button stable beside short progress text', () => {+ const script = read('inject.js');+ assert.match(script, /\.wbs-update-actions\{[^}]*min-width:0/);+ assert.match(script, /\.wbs-update-btn\{[^}]*flex:0 0 112px/);+ assert.match(script, /启动较慢,请稍候…/);+ assert.doesNotMatch(script, /也可双击桌面 .* 图标手动启动/);+});++test('about page reports the running daemon version instead of stale package metadata', () => {+ const daemon = read('daemon.js');+ const aboutStart = daemon.indexOf("p === '/api/about'");+ const updateStart = daemon.indexOf("p === '/api/update-check'", aboutStart);+ assert.ok(aboutStart >= 0 && updateStart > aboutStart);+ const about = daemon.slice(aboutStart, updateStart);+ assert.match(about, /version:\s*DAEMON_VERSION/);+ assert.match(about, /packageVersion/);+ assert.doesNotMatch(about, /build\.version = pjson\.version/);+});++test('update failures preserve stage, attempt id, and apply log details for feedback', () => {+ const daemon = read('daemon.js');+ const inject = read('inject.js');+ assert.match(daemon, /attemptId: updateState\.attemptId/);+ assert.match(daemon, /applyLog: path\.join\(UPDATE_DIR, 'apply\.log'\)/);+ assert.match(inject, /formatUpdateFailure/);+ assert.match(inject, /尝试 ID/);+ assert.match(inject, /日志:/);+ assert.match(inject, /rgba\(226,75,74,\.045\)/);+});++test('update diagnostics persist a redacted local debug log through every major stage', () => {+ const daemon = read('daemon.js');+ const inject = read('inject.js');+ assert.match(daemon, /UPDATE_DEBUG_LOG/);+ assert.match(daemon, /function updateDebug/);+ for (const stage of ['daemon-start', 'check-start', 'check-result', 'download-start', 'download-progress', 'download-verified', 'apply-start', 'apply-script-start']) {+ assert.match(daemon, new RegExp("updateDebug\\('" + stage + "'"));+ }+ assert.match(daemon, /debugLog: UPDATE_DEBUG_LOG/);+ assert.match(daemon, /token\|cookie\|authorization/);+ assert.match(inject, /var runtimeVersion = WBS_VERSION/);+});++test('updaters reject an artifact whose internal daemon version disagrees with its release version', () => {+ const daemon = read('daemon.js');+ const win = read('apply-update.ps1');+ assert.match(daemon, /inspectPackagedApp/);+ assert.match(daemon, /安装包内部 daemon 版本/);+ assert.match(daemon, /artifact-inspect/);+ assert.match(win, /artifact inspect package=/);+ assert.match(win, /更新包内部 daemon 版本/);+ assert.match(win, /新版 daemon 实际版本/);+});++test('sensitive local API routes require an injected token and do not expose wildcard CORS', () => {+ const daemon = read('daemon.js');+ const inject = read('inject.js');+ assert.match(daemon, /API_TOKEN_FILE/);+ assert.match(daemon, /X-WorkDaddy-Token/);+ assert.match(daemon, /isApiRequestAuthorized/);+ assert.match(daemon, /devtools-proxy.*Origin|Origin.*devtools-proxy/);+ assert.doesNotMatch(daemon, /'Access-Control-Allow-Origin': '\*'/);+ assert.match(inject, /__WBS_API_TOKEN__/);+ assert.match(inject, /X-WorkDaddy-Token/);+});++test('DevTools proxy uses the same persisted CDP port fallback as its URL endpoint', () => {+ const daemon = read('daemon.js');+ assert.match(daemon, /const upstreamPort = cdp\.port \|\| readCdpPortFile\(\) \|\| CDP_PORT_HINT \|\| 9222/);+ assert.match(daemon, /devtoolsPort = cdp\.port \|\| readCdpPortFile\(\) \|\| CDP_PORT_HINT \|\| 9222/);+ assert.match(daemon, /uid\.length > 200.*\[\\\\\/\\0\]/);+});++test('automatic updates use the GitHub asset digest and fail closed without one', () => {+ const daemon = read('daemon.js');+ assert.match(daemon, /normalizeAssetSha256\(asset\.digest\)/);+ assert.match(daemon, /dmgSha256/);+ assert.match(daemon, /发布未提供可信的 SHA-256,已停止更新/);+ assert.match(daemon, /validateUpdateArtifact\(target, expectSha\)/);+});++test('update downloads use a unique partial file before atomically promoting the package', () => {+ const daemon = read('daemon.js');+ assert.match(daemon, /const tempTarget = target \+ '\.part\.'/);+ assert.match(daemon, /createWriteStream\(tempTarget/);+ assert.match(daemon, /validateUpdateArtifact\(tempTarget, expectSha\)/);+ assert.match(daemon, /renameSync\(tempTarget, target\)/);+ assert.match(daemon, /updateDownloadPromise/);+ assert.match(daemon, /try \{ digest = sha256File\(file\); \} catch \(e\) \{[\s\S]*安装包 SHA-256 读取失败/);+});++test('account export asks for a non-empty password and import supports an optional password', () => {+ const daemon = read('daemon.js');+ const inject = read('inject.js');+ assert.match(daemon, /password.*不能为空|导出密码不能为空/);+ assert.match(daemon, /randomBytes\(16\)/);+ assert.match(daemon, /version:\s*2/);+ assert.match(daemon, /EXPORT_PASSPHRASE/);+ assert.match(inject, /导出账号.*密码/);+ assert.match(inject, /导入密码可留空/);+ assert.match(inject, /type="password"/);+});+test('zero credits omit the empty-state label', () => {const script = read('inject.js');assert.match(script, /if \(!list\.length\) return Number\(credits\) === 0 \? '' : '<div class="wbs-credit-empty">暂无可用积分<\/div>'/);