From 9504b8ab1a31f5e1a97f4aae01eaa761638b1878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8F=AB=E6=88=91=E5=B0=8F=E6=9D=A8=E5=90=8C=E5=AD=A6?= Date: Mon, 28 Sep 2026 15:39:34 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8F=91=E5=B8=83=201.1.29=EF=BC=8C?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E4=B8=8B=E8=BD=BD=E4=B8=8D=E5=86=8D=E6=8A=8A?= =?UTF-8?q?=20GitHub=20302=20=E5=BD=93=E6=88=90=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 安装包里的 1.1.26 仍用 fetch 拉 github.com/archive,宿主不跟随 302 就报 http 302,切换失败所以版本一直停在旧的 - 下载改走 Node https,302 读 Location;没有 Location 时把 archive 地址改写成 codeload - 自动更新只跟版本号,并在安装前写 stamp,避免 add --force 重启后再次更新 - 钉住的标签只标一条为当前 Co-authored-by: Cursor --- client.js | 8 ++- lib/index.js | 3 +- lib/update.js | 184 +++++++++++++++++++++++++++++++++++++---------- package.json | 2 +- release-notes.md | 18 +++++ 5 files changed, 172 insertions(+), 43 deletions(-) diff --git a/client.js b/client.js index a939082..bb100b8 100644 --- a/client.js +++ b/client.js @@ -892,7 +892,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const next = { stable: "", beta: "" }; for (const id of ["stable", "beta"]) { const list = versions.filter((item) => item.channel === id && keepListedVersion(item, ceiling)); - const hit = preferListed(list, d && d.localVersion); + const hit = preferListed(list, d && d.localVersion, d && d.pin); next[id] = (hit && hit.ref) || ""; } setPick(next); @@ -1279,7 +1279,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const ceiling = listedCeiling(versions, localVer || (updateInfo && updateInfo.localVersion)); const list = versions.filter((item) => item.channel === id && keepListedVersion(item, ceiling)); const selectedRef = pick[id] || ""; - const hit = list.find((item) => item.ref === selectedRef) || preferListed(list, localVer); + const hit = list.find((item) => item.ref === selectedRef) || preferListed(list, localVer, updateInfo && updateInfo.pin); const onLane = channelNow === id; const noBeta = id === "beta" && Array.isArray(updateInfo && updateInfo.versions) && !list.length; const pickedOther = Boolean(hit && selectedRef && !hit.current); @@ -1721,7 +1721,9 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { return listedVersionNewer(ver, ceiling); } - function preferListed(list, localVer) { + function preferListed(list, localVer, pin) { + const pinned = pin ? (list || []).find((item) => item.ref === pin) : null; + if (pinned) return pinned; const ver = String(localVer || "").replace(/^v/i, ""); return (list || []).find((item) => item.current) || (list || []).find((item) => ver && String(item.version || "").replace(/^v/i, "") === ver) diff --git a/lib/index.js b/lib/index.js index 6606262..691bc37 100644 --- a/lib/index.js +++ b/lib/index.js @@ -24,7 +24,8 @@ let bootFullQuit = false; const DEFAULTS = { enabled: true, autoApplyOnStart: true, - autoUpdateOnStart: true, + // 默认关闭开机自动更新:曾因 stamp/SHA 误判触发 dsh add --force 无限重启。 + autoUpdateOnStart: false, autoRevertOnMissing: false, injectOnce: false, stripMnemon: true, diff --git a/lib/update.js b/lib/update.js index acd8651..0cdc14a 100644 --- a/lib/update.js +++ b/lib/update.js @@ -1,6 +1,8 @@ import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import { promises as fsp } from "node:fs"; +import http from "node:http"; +import https from "node:https"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; @@ -62,6 +64,34 @@ function stampPath() { return path.join(findDshHome(), "dsh-purge", "installed-rev"); } +function autoUpdateGuardPath() { + return path.join(findDshHome(), "dsh-purge", "auto-update-guard.json"); +} + +/** 自动更新冷却:防止 dsh add 触发重启后 stamp/版本未对齐又立刻再更一轮。 */ +function autoUpdateGuardBlocks(ref) { + try { + const raw = JSON.parse(fs.readFileSync(autoUpdateGuardPath(), "utf8")); + const at = Date.parse(String(raw?.at || "")) || 0; + if (!at || Date.now() - at > 15 * 60 * 1000) return false; + const target = String(raw?.ref || ""); + if (target && ref && target !== String(ref)) return false; + return true; + } catch { + return false; + } +} + +function markAutoUpdateGuard(ref, sha = "") { + const fp = autoUpdateGuardPath(); + fs.mkdirSync(path.dirname(fp), { recursive: true }); + fs.writeFileSync(fp, `${JSON.stringify({ + ref: String(ref || ""), + sha: String(sha || ""), + at: new Date().toISOString(), + }, null, 2)}\n`, "utf8"); +} + export function normalizeChannel(value) { return String(value || "").toLowerCase() === "beta" ? "beta" : "stable"; } @@ -408,43 +438,98 @@ function detectVia() { function isAbortError(e) { const msg = String((e && e.message) || e || ""); - return (e && (e.name === "AbortError" || e.name === "TimeoutError")) || /aborted|abort/i.test(msg); + return (e && (e.name === "AbortError" || e.name === "TimeoutError")) || /aborted|abort|超时/i.test(msg); +} + +/** github.com/archive 会 302 到 codeload。宿主 fetch 经常把这次跳转原样抛成 http 302,这里直接改写成 codeload。 */ +function rewriteDownloadUrl(url) { + const value = String(url || ""); + let match = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/archive\/refs\/(tags|heads)\/(.+)\.(zip|tar\.gz)$/i); + if (match) { + const kind = match[4].toLowerCase() === "zip" ? "zip" : "tar.gz"; + return `https://codeload.github.com/${match[1]}/${kind}/refs/${match[2]}/${decodeURIComponent(match[3])}`; + } + match = value.match(/^https:\/\/github\.com\/([^/]+\/[^/]+)\/archive\/([0-9a-f]{7,40})\.(zip|tar\.gz)$/i); + if (match) { + const kind = match[3].toLowerCase() === "zip" ? "zip" : "tar.gz"; + return `https://codeload.github.com/${match[1]}/${kind}/${match[2]}`; + } + match = value.match(/^https:\/\/api\.github\.com\/repos\/([^/]+\/[^/]+)\/zipball\/(.+)$/i); + if (match) return `https://codeload.github.com/${match[1]}/zip/refs/tags/${decodeURIComponent(match[2])}`; + return ""; +} + +function requestBuffer(url, ms, headers, redirectsLeft = 5) { + return new Promise((resolve, reject) => { + let parsed; + try { + parsed = new URL(url); + } catch (e) { + reject(e); + return; + } + const lib = parsed.protocol === "http:" ? http : https; + const req = lib.request(parsed, { + method: "GET", + headers: { "user-agent": "dsh-purge-update", accept: "*/*", ...headers }, + }, (res) => { + const status = res.statusCode || 0; + if ([301, 302, 303, 307, 308].includes(status)) { + res.resume(); + if (redirectsLeft <= 0) { + reject(new Error("http redirect loop")); + return; + } + const loc = res.headers.location; + const next = loc ? new URL(loc, url).href : rewriteDownloadUrl(url); + if (!next || next === url) { + reject(new Error(`http ${status}`)); + return; + } + requestBuffer(next, ms, headers, redirectsLeft - 1).then(resolve, reject); + return; + } + if (status < 200 || status >= 300) { + res.resume(); + const rewritten = rewriteDownloadUrl(url); + if (rewritten && rewritten !== url && redirectsLeft > 0) { + requestBuffer(rewritten, ms, headers, redirectsLeft - 1).then(resolve, reject); + return; + } + reject(new Error(`http ${status}`)); + return; + } + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => resolve({ status, body: Buffer.concat(chunks) })); + res.on("error", reject); + }); + req.on("error", reject); + req.setTimeout(ms, () => { + req.destroy(new Error("GitHub 超时")); + }); + req.end(); + }); } async function fetchRes(url, ms = 20000, headers = {}) { - const ctrl = new AbortController(); - const timer = setTimeout(() => { - try { - ctrl.abort("timeout"); - } catch { - ctrl.abort(); - } - }, ms); + const started = rewriteDownloadUrl(url) || url; try { - let current = String(url || ""); - for (let hop = 0; hop < 6; hop += 1) { - const res = await fetch(current, { - headers: { "user-agent": "dsh-purge-update", accept: "*/*", ...headers }, - // 手动跟跳转:部分宿主对 github.com → codeload 跨域 302 不会自动 follow,会直接抛 http 302。 - redirect: "manual", - cache: "no-store", - signal: ctrl.signal, - }); - if ([301, 302, 303, 307, 308].includes(res.status)) { - const loc = res.headers.get("location"); - if (!loc) throw new Error(`http ${res.status}`); - current = new URL(loc, current).href; - continue; - } - if (!res.ok) throw new Error(`http ${res.status}`); - return res; - } - throw new Error("http redirect loop"); + const result = await requestBuffer(started, ms, headers); + return { + ok: true, + status: result.status, + async text() { + return result.body.toString("utf8"); + }, + async arrayBuffer() { + const copy = Buffer.from(result.body); + return copy.buffer.slice(copy.byteOffset, copy.byteOffset + copy.byteLength); + }, + }; } catch (e) { - if (isAbortError(e)) throw new Error("GitHub 超时"); + if (isAbortError(e) || /GitHub 超时/.test(String(e && e.message))) throw new Error("GitHub 超时"); throw e; - } finally { - clearTimeout(timer); } } @@ -541,9 +626,9 @@ export function markCurrent(versions, state, localVer, localSha) { && String(item.version || "").replace(/^v/i, "") === ver )); return rows.map((item) => { - const shaHit = Boolean(localSha && item.sha && sameRev(localSha, item.sha)); + const shaHit = Boolean(!pin && localSha && item.sha && sameRev(localSha, item.sha)); const pinHit = Boolean(pin && item.ref === pin); - // 提交号对不上时,只把本通道里和本机版本号相同的那一条标成当前。 + // 钉住某个标签时只标那一条,避免 master 的提交号也显示成「当前」。 const headHit = Boolean( !pin && !shaMatched @@ -555,7 +640,7 @@ export function markCurrent(versions, state, localVer, localSha) { return { ...item, shaShort: item.shaShort || (item.sha ? String(item.sha).slice(0, 7) : ""), - current: shaHit || pinHit || headHit, + current: pinHit || shaHit || headHit, }; }); } @@ -713,10 +798,12 @@ function describeLane(id, listed, state, localVer, localRev) { const current = matchesHead || versions.some((item) => item.current && (item.latest || (state.pin && item.ref === state.pin))); let hasUpdate = false; if (onLane && state.pin) { + // 钉住某标签时:只看是否已装到该提交。 hasUpdate = Boolean(sha && localRev && !sameRev(localRev, sha)); - } else if (onLane && sha && localRev) { - hasUpdate = !sameRev(localRev, sha) || versionIsNewer(version, localVer); } else if (onLane && versionIsNewer(version, localVer)) { + // 正常通道:只按版本号升级,避免 zip/dsh 安装后 stamp 未写完就因 SHA 漂移反复 add --force 重启。 + hasUpdate = true; + } else if (onLane && !localVer && sha && localRev && !sameRev(localRev, sha)) { hasUpdate = true; } return { @@ -953,6 +1040,10 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) { const ref = safeUpdateRef(options.ref || currentChannelRef(state) || STABLE_REF); if (!ref) throw new Error("未知版本"); const force = options.force !== false; + // 先写入目标 sha:dsh plugin add --force 可能当场重启宿主,若 stamp 写在后面会永远对不上 → 开机无限更新重启。 + const plannedSha = (await remoteHeadSha(ref).catch(() => "")) || ""; + if (plannedSha) writeStamp(plannedSha); + if (options.auto === true) markAutoUpdateGuard(ref, plannedSha); const zipDirs = []; const vias = new Set(); for (const job of jobs) { @@ -983,7 +1074,7 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) { await overlayFromZip(zipDirs, ref); vias.add("zip"); } - const sha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || (await remoteHeadSha(ref).catch(() => "")); + const sha = (gitOk() ? gitHead(PLUGIN_ROOT) : "") || plannedSha || (await remoteHeadSha(ref).catch(() => "")); if (sha) writeStamp(sha); const via = vias.size > 1 ? "mixed" : [...vias][0] || detectVia(); const pin = options.pin === false ? "" : (options.pin || state.pin || ""); @@ -1103,10 +1194,26 @@ export async function autoUpdateIfNeeded() { try { const check = await checkUpdate(); if (check.pinned) return rememberUpdate({ ...check, auto: true, skipped: "pinned" }); + const lane = check.lanes?.[check.channel] || check.lanes?.stable || {}; + const remoteVer = String(lane.version || "").replace(/^v/i, ""); + const localVer = String(check.localVersion || "").replace(/^v/i, ""); + // 自动更新只跟版本号,不追 master SHA,避免 stamp 未写完时反复 add --force 重启。 + if (!versionIsNewer(remoteVer, localVer)) { + return rememberUpdate({ ...check, auto: true, hasUpdate: false, skipped: "latest" }); + } if (!check.hasUpdate) return rememberUpdate({ ...check, auto: true, skipped: "latest" }); if (check.updateTarget === BETA_REF && readChannelState().channel !== "beta") { return rememberUpdate({ ...check, auto: true, skipped: "beta" }); } + const target = currentChannelRef(); + if (autoUpdateGuardBlocks(target)) { + return rememberUpdate({ + ...check, + auto: true, + skipped: "cooldown", + error: "刚刚自动更新过,跳过本轮以免重启循环", + }); + } const jobs = planUpdates(); const dirtyGit = jobs.filter((j) => j.kind === "git" && gitTrackedDirty(j.dir)); const runnable = jobs.filter((j) => !(j.kind === "git" && gitTrackedDirty(j.dir))); @@ -1119,10 +1226,11 @@ export async function autoUpdateIfNeeded() { }); } const applied = await applyUpdate(runnable, { - ref: currentChannelRef(), + ref: target, channel: readChannelState().channel, pin: false, force: false, + auto: true, }); return rememberUpdate({ ...applied, auto: true }); } catch (e) { diff --git a/package.json b/package.json index 51af758..88ffaf2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.28", + "version": "1.1.29", "description": "DeepSeek Harness 网络安全红队工具:本机官方 Harness 受控评测与清洗,不同模型可换不同提示词;默认提示词面向国模「小码酱」。求 Star ⭐", "type": "module", "main": "lib/index.js", diff --git a/release-notes.md b/release-notes.md index 82bf6e5..0ca3025 100644 --- a/release-notes.md +++ b/release-notes.md @@ -1,3 +1,21 @@ +# 1.1.29 + +## 中文 + +- **修复选版本/重装后无限重启**:`dsh plugin add --force` 会先杀掉宿主,若 `installed-rev` 写在后面,下次启动又判定要更新,形成死循环。 +- 自动更新改为**只跟版本号**,不再因 master SHA 漂移反复安装;更新前先写 stamp,并加 15 分钟冷却。 +- 默认关闭 `autoUpdateOnStart`(可在配置里手动打开)。 +- **修复更新仍报 `http 302`**:下载改用 Node `https`,`github.com/archive` 即使没有 Location 也改写成 `codeload`,不再走宿主 fetch。 +- **修复切换版本后仍显示旧版本**:钉住的标签只标那一条为当前。 + +## English + +- **Fix infinite restart after switching versions / reinstall**: `dsh plugin add --force` can kill the host before `installed-rev` is written, so the next boot thinks an update is still needed. +- Auto-update follows **version numbers only** (not floating master SHA); write the stamp before install and add a 15-minute cooldown. +- `autoUpdateOnStart` defaults to off (can still be enabled in config). +- **Fix update still failing with `http 302`**: download via Node `https`, and rewrite `github.com/archive` to `codeload` even when Location is missing. +- **Fix switch still showing the old version**: a pinned tag is the only row marked current. + # 1.1.28 ## 中文