From 265f859ef3b6c24186eb8384d1638c4cf211b2c3 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?= <188421097+HunYiSage@users.noreply.github.com> Date: Fri, 9 Oct 2026 01:32:17 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=8F=91=E5=B8=83=201.1.66=EF=BC=8CHook?= =?UTF-8?q?s=20=E5=BC=80=E5=85=B3=E4=B8=8E=E4=BC=9A=E8=AF=9D=E6=9D=A5?= =?UTF-8?q?=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 清洗页可关掉 hooks deny 旁路。继续/拒答续跑改用官方允许的来源 kind,限流和传输失败不再自动续一轮。 Closes #80. Closes #81. Co-authored-by: Cursor --- README.md | 17 +-- README.zh-CN.md | 55 ++++---- client.js | 102 ++++++++++++++- cordis.patch.yml | 1 + lib/continue-retry.js | 27 +++- lib/core.js | 261 +++++++++++++++++++++++++++++++++++++- lib/hooks-deny.js | 217 +++++++++++++++++++++++++++++++ lib/identity.js | 17 +++ lib/index.js | 93 ++++++++++++-- lib/redteam/store-core.js | 33 +++++ lib/refusal-recover.js | 3 +- package.json | 2 +- release-notes.md | 20 +++ 13 files changed, 789 insertions(+), 59 deletions(-) create mode 100644 lib/hooks-deny.js diff --git a/README.md b/README.md index b24cbac..888395d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

⚔️ DeepSeek Harness cybersecurity red-team tool (dsh-purge)

-

Version 1.1.65

+

Version 1.1.66

DeepSeek Harness jailbreak: every model, swap prompts per model. Default prompt for 小码酱. Please star ⭐ If you build on this, see Attribution required. @@ -134,7 +134,7 @@ Using them without attribution, hiding the source, or passing them off as your o Pick the plugin that matches your dsh. The latest plugin supports **dsh 0.2** only. Older dsh builds need the matching older plugin. Do not apply this release to 0.1.x. -- **dsh 0.2** (official desktop **0.2.0-rc.2** / official `dsh web`): use **1.1.40** or newer. The current release is **1.1.65**. The install commands on this page install that line. +- **dsh 0.2** (official desktop **0.2.0-rc.2** / official `dsh web`): use **1.1.40** or newer. The current release is **1.1.66**. The install commands on this page install that line. - **dsh 0.1.7** (including **0.1.7-rc.1** and **0.1.7-rc.2**): use **1.1.39** or older. Pick the tag on [Releases](https://github.com/YuJunZhiXue/dsh-purge/releases). Unmatched patches stay pending or skipped. Nothing is rewritten blindly. @@ -205,13 +205,13 @@ Official desktop 0.2 loads the `desktop` profile. Do not use `default`, and do n

🌐 Open Hub page  ·  - 🚀 Install in desktop client + 🚀 Install in desktop client

🔗 **Raw protocol URL:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.65&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.66&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz ```
@@ -227,7 +227,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.65', + version: '1.1.66', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -246,7 +246,7 @@ export function installDshPurgeToDesktop() { **HTML link:** ```html - + 🚀 Install in desktop client ``` @@ -257,7 +257,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | Plugin id | | name | `dsh-purge` | Display name | -| version | `1.1.65` | Semver | +| version | `1.1.66` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub source archive | @@ -584,7 +584,6 @@ On the Clean page, under Prompt. One host per line, then Save list. Steps are in | dsh-purge | button beside the session title; opens or collapses the dock | | Clean | the old Rules page: patches, prompt, rule sets, skills | | Drill | assets, skills, and environment after authorization. The tab says Unauthorized until then | -| Light / Ink | card appearance | | Patches | grouped status, Apply, Restore, or Uninstall | | Prompt | edit `prompt-inject.md` as the session override | | Own servers | one IP or exact hostname per line, saved to `$DSH_HOME/net-scope-allow.txt` | @@ -641,8 +640,6 @@ The box sits under Prompt. If the dock does not show it yet, quit DeepSeek Harne `203.0.113.10` and `example.com` above are only examples of the form. Replace them with your own host before you save. -![Own servers](docs/preview/own-servers-en.png) - --- ## Local checks diff --git a/README.zh-CN.md b/README.zh-CN.md index fa41896..21cb0a1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1,15 +1,29 @@ +

+ dsh-purge +

+

⚔️ DeepSeek Harness 网络安全红队工具(dsh-purge)

-# ⚔️ DeepSeek Harness 网络安全红队工具(dsh-purge) +

Version 1.1.66

-**Version 1.1.65** +

+ DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分 +

-*DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分* +

+ GitHub stars + MIT license + awesome · DSH plugin + DeepSeek Harness Hub + DSH +
+ Node.js + JavaScript +

- - - -[English](README.md) | [中文](README.zh-CN.md) +

+ English | 中文 +

> **官方 Web 和官方桌面端都支持。** 官方 `dsh web` 用 profile `web`;官方桌面 EXE(DeepSeek Harness **0.2.0-rc.2**)用 profile `desktop`。两边分开安装、分开点「应用」。当前版本只适配 dsh 0.2;更早的 dsh 用对应的老版本插件。社区桌面端不维护。 > @@ -33,7 +47,7 @@ --- - + ## ☕ 赞助 @@ -124,7 +138,7 @@ Harness 不只是把问题交给模型。它还会在运行时改提示词、审 请选择支持的版本。最新版只支持 **dsh 0.2**。更早的 dsh 使用对应的老版本插件,不要拿当前版本去打 0.1.x。 -- **dsh 0.2**(官方桌面 **0.2.0-rc.2** / 官方 `dsh web`):用 **1.1.40** 及以上,当前是 **1.1.65**。本页安装命令装的就是这一档。 +- **dsh 0.2**(官方桌面 **0.2.0-rc.2** / 官方 `dsh web`):用 **1.1.40** 及以上,当前是 **1.1.66**。本页安装命令装的就是这一档。 - **dsh 0.1.7**(含 **0.1.7-rc.1**、**0.1.7-rc.2**):用 **1.1.39** 及更早。[Releases](https://github.com/YuJunZhiXue/dsh-purge/releases) 里选对应标签。 对不上的补丁会显示待应用或跳过,不会乱改文件。 @@ -199,7 +213,7 @@ dsh plugin --profile desktop add https://github.com/YuJunZhiXue/dsh-purge/archiv 🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.65&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.66&repo=YuJunZhiXue%2Fdsh-purge&permissions=%E7%B3%BB%E7%BB%9F%E6%8F%90%E7%A4%BA%E8%AF%8D%E6%B3%A8%E5%85%A5%2C%E6%9C%AC%E6%9C%BA%E8%A1%A5%E4%B8%81%2C%E8%AE%BE%E7%BD%AE%E9%A1%B5&downloadUrl=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fdsh-purge%2Farchive%2Frefs%2Fheads%2Fmaster.tar.gz ``` **协议参数和网页触发代码** @@ -214,7 +228,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.65', + version: '1.1.66', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz', @@ -233,7 +247,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -245,7 +259,7 @@ export function installDshPurgeToDesktop() { | ----------- | --------------------------------------------------------------------------- | ------------ | | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.65` | 语义化版本号 | +| version | `1.1.66` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.tar.gz` | GitHub 源码包地址 | @@ -553,29 +567,29 @@ dsh-purge --uninstall **清洗** -清洗 +![清洗](docs/preview/dock-clean.png) **演练台授权** -演练台授权 +![演练台授权](docs/preview/dock-auth.png) **演练台** -演练台 +![演练台](docs/preview/dock-drill.png) **补丁** -补丁 +![补丁](docs/preview/settings.png) **规则集** -规则集 +![规则集](docs/preview/rules.png) **自己的服务器** 在清洗页,提示词下面。每行一台,点保存名单。步骤见 [自己的服务器](#自己的服务器)。 -自己的服务器 +![自己的服务器](docs/preview/own-servers.png) | 区域 | 说明 | @@ -583,7 +597,6 @@ dsh-purge --uninstall | dsh-purge | 会话标题旁的按钮,打开或收起右侧栏 | | 清洗 | 原来的规则设定:补丁、提示词、规则集、Skill | | 演练台 | 授权后的资产、技能与环境页。未授权时按钮标「未授权」 | -| | | | 补丁 | 分组查看状态,应用、还原或卸载 | | 提示词 | 编辑 `prompt-inject.md`,作为会话覆盖段 | | 自己的服务器 | 每行登记一个 IP 或完整主机名,保存后写入 `$DSH_HOME/net-scope-allow.txt` | @@ -644,8 +657,6 @@ purge_status purge_apply purge_revert 上面的 `203.0.113.10` 和 `example.com` 只是写法示例,不是放行地址。把它们换成你自己的那一台再保存。 -自己的服务器 - --- ## 本地校验 diff --git a/client.js b/client.js index af70e20..54bdba6 100644 --- a/client.js +++ b/client.js @@ -188,6 +188,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "table.patch": "项目", "table.status": "状态", "status.applied": "已应用", + "status.off": "已关闭", "status.pending": "待应用", "status.unmatched": "没对上", "status.skipped": "跳过", @@ -199,7 +200,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "warn.noInject": "官方始终用默认提示词。红队开了规则集就只用规则集;没开时用去掉 CTF 的默认提示词,再接红队操作。两边都空会提示必须添加。", "need.prompt": "提示词和规则集都是空的,必须先添加提示词,或启用一条有内容的规则集。", "btn.restoreInject": "恢复默认", - "saved.restoreInject": "已填入默认提示词,点保存写入", + "saved.restoreInject": "已恢复默认提示词", "skip": "跳过", "unknown": "未知", "delete": "删除", @@ -416,6 +417,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "rewind.once.hint": "把这一轮发出去的那句放回输入框,并清掉这一轮", "rewind.round": "回退上一轮", "rewind.round.hint": "把这一轮发出去的那句放回输入框;子代理也只撤这一轮", + "hooksDeny.title": "Hooks 拦截", + "hooksDeny.bypass": "放行 hooks 的 deny / ask(补丁 30 / 31 / 64 / 65)", + "hooksDeny.hint": "关掉后,用户自己的 PreToolUse / UserPromptSubmit / Stop hook 的 deny 会按官方逻辑生效。官方 ask 分支本身是空操作,关开关不会弹出审批框。改完后点「应用」并重启才写进宿主。", + "saved.hooksDeny": "已保存", "continue.title": "失败重试 / 继续", "continue.hint": "请求失败会自动重试;异常停止或中断可点「继续」或自动续跑。自己点停止不会自动继续。次数用完后需新开一轮。", "continue.autoRetry": "失败自动重试", @@ -500,6 +505,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "table.patch": "Item", "table.status": "Status", "status.applied": "Applied", + "status.off": "Off", "status.pending": "Pending", "status.unmatched": "No match", "status.skipped": "Skipped", @@ -511,7 +517,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "warn.noInject": "Official mode always uses the default prompt. Red team uses only the active rule set; otherwise it uses the default prompt without the CTF section, then the red team steps. If both are empty you will be asked to add a prompt.", "need.prompt": "Both the prompt and the rule set are empty. Add a prompt, or enable a rule that has content.", "btn.restoreInject": "Reset default", - "saved.restoreInject": "Default prompt loaded. Save to write.", + "saved.restoreInject": "Default prompt restored", "skip": "Skipped", "unknown": "Unknown", "delete": "Delete", @@ -728,6 +734,10 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { "rewind.once.hint": "Put this round's message back in the box and drop only this round", "rewind.round": "Undo last round", "rewind.round.hint": "Put this round's message back in the box; subagents drop only this round", + "hooksDeny.title": "Hook interception", + "hooksDeny.bypass": "Bypass hook deny / ask (patches 30 / 31 / 64 / 65)", + "hooksDeny.hint": "When off, your own PreToolUse / UserPromptSubmit / Stop hook deny runs as the official host wrote it. The official ask branch is a no-op; turning this off will not show an approval dialog. Click Apply and restart to write the host files.", + "saved.hooksDeny": "Saved", "continue.title": "Retry / Continue", "continue.hint": "Failed requests auto-retry. After an abnormal stop or interrupt, use Continue or auto-resume. A manual stop never auto-continues. Counts reset after a completed turn.", "continue.autoRetry": "Auto-retry on failure", @@ -973,12 +983,13 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds if (st === "pending") return "wait"; if (st === "unmatched") return "bad"; if (st === "na") return "ok"; - if (st === "missing_file" || st === "skipped" || st === "unlocated") return "miss"; + if (st === "missing_file" || st === "skipped" || st === "unlocated" || st === "off") return "miss"; return "bad"; } function statusLabel(st, t) { if (st === "applied" || st === "already") return t("status.applied"); + if (st === "off") return t("status.skipped"); if (st === "pending") return t("status.pending"); if (st === "unmatched") return t("status.unmatched"); if (st === "skipped") return t("status.skipped"); @@ -1096,6 +1107,61 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds }); } + function HooksDenySection({ onSaved }) { + const t = useT(); + const [cfg, setCfg] = useState(null); + const [notice, setNotice] = useState({ kind: "idle", text: "" }); + const [busy, setBusy] = useState(false); + + useEffect(() => { + apiJson("/dsh-purge/hooks-deny") + .then((d) => { if (d && d.ok) setCfg({ hooksDenyBypass: d.hooksDenyBypass !== false }); }) + .catch(() => {}); + }, []); + + const save = (hooksDenyBypass) => { + if (!cfg || busy) return; + setCfg({ hooksDenyBypass }); + setBusy(true); + apiJson("/dsh-purge/hooks-deny", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ hooksDenyBypass }), + }) + .then((d) => { + if (d && d.ok) { + setCfg({ hooksDenyBypass: d.hooksDenyBypass === true }); + setNotice({ kind: "ok", text: t("saved.hooksDeny") }); + if (typeof onSaved === "function") onSaved(); + } else { + setNotice({ kind: "error", text: t("err.save", { error: (d && d.error) || "" }) }); + } + }) + .catch((e) => setNotice({ kind: "error", text: t("err.save", { error: e.message }) })) + .finally(() => setBusy(false)); + }; + + if (!cfg) return null; + return h("div", { className: "dshp-cr", style: { marginTop: 12 } }, + h("div", { className: "dshp-sub" }, + h("h4", null, t("hooksDeny.title")), + noticeNode(notice), + ), + h("p", { className: "dshp-hint", style: { margin: "0 0 4px", color: "var(--dshp-mute)", fontSize: 12 } }, t("hooksDeny.hint")), + h("div", { className: "dshp-cr-row" }, + h("label", null, + h("input", { + type: "checkbox", + checked: cfg.hooksDenyBypass === true, + disabled: busy, + onChange: (e) => save(e.target.checked), + }), + t("hooksDeny.bypass"), + ), + ), + ); + } + function ContinueRetrySection() { const t = useT(); const [cfg, setCfg] = useState(null); @@ -1597,9 +1663,36 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds const restoreOverride = useCallback(() => { if (!defaultOverride) return; + const tr = t; + const ticket = ++actionTicket.current; overrideRef.current = defaultOverride; setOverride(defaultOverride); - setNotice({ kind: "ok", text: t("saved.restoreInject") }); + setPatchBusy(true); + setNotice({ kind: "idle", text: "" }); + apiJson("/dsh-purge/override", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ content: defaultOverride }), + }) + .then((d) => { + if (ticket !== actionTicket.current) return; + if (!d || !d.ok) { + setNotice({ kind: "error", text: tr("err.save", { error: (d && d.error) || "" }) }); + return; + } + if (typeof d.content === "string") { + overrideRef.current = d.content; + setOverride(d.content); + } + setNotice({ kind: "ok", text: tr("saved.restoreInject") }); + }) + .catch((e) => { + if (ticket !== actionTicket.current) return; + setNotice({ kind: "error", text: tr("err.save", { error: e.message }) }); + }) + .finally(() => { + if (ticket === actionTicket.current) setPatchBusy(false); + }); }, [defaultOverride, t]); const waitHostAfterUninstall = useCallback((tr) => { @@ -1777,6 +1870,7 @@ body:not([data-ds-dark-theme]) .dshp-auth-ops button.primary{background:var(--ds ), h("div", { className: "dshp-bar", "aria-hidden": "true" }, h("i", { style: { width: pct + "%" } })), h(PatchGroups, { state: s }), + h(HooksDenySection, { onSaved: loadAll }), h("div", { className: "dshp-row", style: { marginTop: 14 } }, h(Btn, { kind: "primary", disabled: patchBusy || uninstallBusy || !overrideLoaded, onClick: () => doAction("apply", "action.apply") }, patchBusy ? t("btn.apply.busy") : t("btn.apply")), h(Btn, { kind: "danger", disabled: patchBusy || uninstallBusy, onClick: () => doAction("revert", "action.revert") }, t("btn.revert")), diff --git a/cordis.patch.yml b/cordis.patch.yml index 00d5c74..3e7de13 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -49,6 +49,7 @@ continueMax: 3 continueText: "继续" capabilityProtocol: true + hooksDenyBypass: true # 演练台:预设 + 技能落地(本插件 lib/redteam) - id: dsh-purge-redteam diff --git a/lib/continue-retry.js b/lib/continue-retry.js index 8dca8d1..fabc5bf 100644 --- a/lib/continue-retry.js +++ b/lib/continue-retry.js @@ -17,10 +17,22 @@ const PERMANENT_CODES = new Set([ "INVALID", "INVALID_REQUEST", "QUOTA", + "ACCOUNT_QUOTA", "BILLING", "MODEL_NOT_FOUND", "CONTEXT_OVERFLOW", "CONTEXT_LENGTH", + "CONTEXT_WINDOW_EXCEEDED", + "NO_ADAPTER", + "MISSING_CREDENTIAL", + "INVALID_CREDENTIAL", +]); + +/** Official already retried these; a new "继续" turn cannot clear them. */ +const NO_CONTINUE_CODES = new Set([ + ...PERMANENT_CODES, + "RATE_LIMIT", + "TRANSPORT", ]); const ABNORMAL_KINDS = new Set(["error", "aborted", "interrupted", "max-tokens"]); @@ -87,8 +99,15 @@ export function isAbnormalReason(reason) { return Boolean(reason && ABNORMAL_KINDS.has(reason.kind)); } +export function failureCodeOf(reason) { + const raw = reason?.error?.code ?? reason?.failure?.code ?? reason?.code; + return String(raw || "").toUpperCase(); +} + export function shouldAutoContinue(reason) { - return isAbnormalReason(reason) && !isUserAbort(reason); + if (!isAbnormalReason(reason) || isUserAbort(reason)) return false; + const code = failureCodeOf(reason); + return !code || !NO_CONTINUE_CODES.has(code); } export function isPermanentFailure(code) { @@ -107,8 +126,7 @@ export function makeContinueMessage(text) { role: "user", content: [{ type: "text", text: body }], source: { - kind: "plugin", - plugin: "dsh-purge", + kind: "dsh-purge", form: "notice", summary: "continue", }, @@ -195,7 +213,8 @@ export function hasFreshHumanTurn(events) { const after = end ? list.filter((event) => (event?.seq || 0) > end.seq) : list; return after.some((event) => { if (event?.type !== "user/message") return false; - return event.data?.source?.kind !== "plugin"; + const kind = event.data?.source?.kind; + return kind !== "plugin" && kind !== "dsh-purge"; }); } diff --git a/lib/core.js b/lib/core.js index f013bcc..d915ff7 100644 --- a/lib/core.js +++ b/lib/core.js @@ -28,6 +28,7 @@ import { import { adapterFor, detectSurface } from "./surface.js"; import { hostPromptKeepsInject } from "./host-clean.js"; import { openSlot } from "./table-read.js"; +import * as hooksDeny from "./hooks-deny.js"; // 无归档时用 node:fs;app.asar 还在时改写真实的 resources/app,避免新建文件 ENOENT。 const fs = hostFs; @@ -1775,6 +1776,11 @@ async function resolveAiBaseForApply(aiBase, options = {}) { } export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) { + const settings = options.hooksDeny?.settings || getHooksDenySettings(); + const pick = options.hooksDeny?.selectPatches || hooksDeny.selectPatches; + const selected = pick(patches, settings); + const hookDenyRestoreFailed = []; + const hookDenyRestoreChanged = []; const hosts = []; const seen = new Set(); for (const raw of enumeratePatchAiBases()) { @@ -1784,7 +1790,12 @@ export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) if (seen.has(key)) continue; seen.add(key); await backupAll(aiBase); - const report = await applyPatches(aiBase, patches, options); + if (settings.hooksDenyBypass === false) { + const restored = await restoreHookDenyForBases([aiBase]); + hookDenyRestoreFailed.push(...restored.failed); + hookDenyRestoreChanged.push(...restored.changed); + } + const report = await applyPatches(aiBase, selected, options); hosts.push({ aiBase, report, @@ -1793,7 +1804,12 @@ export async function applyPatchesAllHosts(patches = ALL_PATCHES, options = {}) flash: silenceCmdFlash(aiBase), }); } - return { hosts, report: mergeApplyReports(hosts.map((h) => h.report)) }; + return { + hosts, + report: mergeApplyReports(hosts.map((h) => h.report)), + hookDenyRestoreFailed, + hookDenyRestoreChanged, + }; } export async function revertAllHosts(options = {}) { @@ -4267,6 +4283,47 @@ const NEW_TOOL_PATCHES = [ ], markers: ["[dsh-purge] prepare assemble before this step"], }, + { + id: 81, + name: "HUNG_PROMPT_EVERY_STEP", + layer: "代码", + layer_en: "Code", + desc: "每一步用同一份 prompt-inject 全文,第二轮不再把注入换掉 / keep the hung prompt-inject on every step", + file: ["agent-loop"], + skipIfMarked: true, + replacements: [ + { + pattern: + "\t\tconst dshPurgePrepare = globalThis.__dshPurgePrepareAssemble;\n" + + "\t\tif (typeof dshPurgePrepare === \"function\") {\n" + + "\t\t\ttry { dshPurgePrepare(this.loopCtx); } catch { /* [dsh-purge] prepare assemble before this step */ }\n" + + "\t\t}\n" + + "\t\tconst assembly = await this.loopCtx.systemPrompt.assemble(assembleContextFor(this, signal));", + replace: + "\t\tconst dshPurgePrepare = globalThis.__dshPurgePrepareAssemble;\n" + + "\t\tlet dshPurgePrompt = null;\n" + + "\t\tif (typeof dshPurgePrepare === \"function\") {\n" + + "\t\t\ttry { dshPurgePrompt = dshPurgePrepare(this.loopCtx); } catch { /* [dsh-purge] prepare assemble before this step */ }\n" + + "\t\t}\n" + + "\t\tconst dshPurgeAssemble = dshPurgePrompt && typeof dshPurgePrompt.assemble === \"function\" ? dshPurgePrompt : this.loopCtx.systemPrompt;\n" + + "\t\tconst assembly = await dshPurgeAssemble.assemble(assembleContextFor(this, signal));", + }, + { + pattern: + "\t\tconst { assembly } = decision;\n" + + "\t\tconst renderedPrompt = renderPrompt(assembly);", + replace: + "\t\tconst { assembly } = decision;\n" + + "\t\tlet renderedPrompt = renderPrompt(assembly);\n" + + "\t\tconst dshPurgeHung = typeof globalThis.__dshPurgeHungPrompt === \"function\" ? globalThis.__dshPurgeHungPrompt() : \"\";\n" + + "\t\tconst dshPurgeNeedle = String(dshPurgeHung || \"\").trim().slice(0, 96);\n" + + "\t\tif (dshPurgeNeedle && !String(renderedPrompt || \"\").includes(dshPurgeNeedle)) {\n" + + "\t\t\trenderedPrompt = String(dshPurgeHung).trim() + (renderedPrompt ? \"\\n\\n\" + renderedPrompt : \"\"); // [dsh-purge] hang full prompt-inject every step\n" + + "\t\t}", + }, + ], + markers: ["[dsh-purge] hang full prompt-inject every step"], + }, { id: 66, name: "SYSTEM_PROMPT_RENDER_GUARD", @@ -5026,6 +5083,16 @@ const NEW_TOOL_PATCHES = [ '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";\n' + '\t\t\tagent.steer(createUserMessage({', }, + { + pattern: + '\t\tif (merged.decision === "deny") {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";\n' + + '\t\t\tagent.steer(createUserMessage({', + replace: + '\t\tif (merged.decision === "deny") {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";\n' + + '\t\t\tagent.steer(createUserMessage({', + }, ], markers: ["[dsh-purge] Stop hook steer disabled"], }, @@ -5046,9 +5113,53 @@ const NEW_TOOL_PATCHES = [ '\t\tif (merged.decision === "deny") { /* [dsh-purge] UserPromptSubmit deny→allow */ }\n' + '\t\telse if (merged.decision === "__dsh_purge_deny_disabled__") { /* [dsh-purge] pre-step reject disabled */ }', }, + { + pattern: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, ], markers: ["[dsh-purge] UserPromptSubmit deny→allow"], }, + { + id: 78, + name: "OVERLAY_RESTORE_FROM_BAK", + layer: "代码", + layer_en: "Code", + desc: "声明过的补丁文件不见时,从 .dshpurge.bak 拷回再加载 / restore a missing declared overlay from its bak", + file: ["app-boot"], + optional: true, + skipIfMarked: true, + replacements: [ + { + pattern: + "function loadOverlayPatches(binName, file) {\n" + + "\tlet content;\n" + + "\ttry {\n" + + "\t\tcontent = readFileSync(file, \"utf8\");\n" + + "\t} catch (error) {\n" + + "\t\tthrow new Error(`${binName}: failed to read overlay ${file}: ${String(error)}`);\n" + + "\t}\n" + + "\treturn parsePatchList(binName, file, content, \"overlay\");\n" + + "}", + replace: + "function loadOverlayPatches(binName, file) {\n" + + "\tlet content;\n" + + "\ttry {\n" + + "\t\tcontent = readFileSync(file, \"utf8\");\n" + + "\t} catch (error) {\n" + + "\t\tconst bak = file + \".dshpurge.bak\"; // [dsh-purge] restore missing overlay from bak\n" + + "\t\tif (error && error.code === \"ENOENT\" && fs.existsSync(bak)) {\n" + + "\t\t\ttry { fs.copyFileSync(bak, file); content = readFileSync(file, \"utf8\"); }\n" + + "\t\t\tcatch { /* bak restore failed */ }\n" + + "\t\t}\n" + + "\t\tif (content === void 0) throw new Error(`${binName}: failed to read overlay ${file}: ${String(error)}`);\n" + + "\t}\n" + + "\treturn parsePatchList(binName, file, content, \"overlay\");\n" + + "}", + }, + ], + markers: ["[dsh-purge] restore missing overlay from bak"], + }, ]; export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES]; @@ -5181,6 +5292,79 @@ export async function dropStaleUserProfilePatchBackups(dshHome = findDshHome()) return dropped; } +const BAK_SUFFIX = ".dshpurge.bak"; + +function shouldRestoreOriginal(original, bak) { + if (isUserProfilePatchFile(original)) return false; + let bakStat; + try { + bakStat = fs.statSync(bak); + } catch { + return false; + } + if (!bakStat.isFile() || bakStat.size <= 0) return false; + try { + const st = fs.statSync(original); + if (!st.isFile() || st.size > 0) return false; + } catch (e) { + if (!e || e.code !== "ENOENT") return false; + } + return true; +} + +/** + * 正式文件不见、或被写成空文件时,从旁边的 .dshpurge.bak 拷回去。 + * 不删 bak。targetFiles 只认还在的文件,所以丢了以后还原/应用都看不见这份备份。 + * @returns 已拷回的正式路径 + */ +export function restoreMissingOriginalsFromBak(aiBase) { + const restored = []; + if (!aiBase || !isDir(aiBase)) return restored; + const roots = [aiBase]; + const nested = path.join(aiBase, "dsh", "node_modules", "@deepseek-ai"); + if (isDir(nested)) roots.push(nested); + const visit = (dir, depth) => { + if (depth > 5) return; + let ents = []; + try { + ents = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const ent of ents) { + if (ent.name === "node_modules" || ent.name === ".git") continue; + const fp = path.join(dir, ent.name); + if (ent.isDirectory()) { + visit(fp, depth + 1); + continue; + } + if (!ent.isFile() || !ent.name.endsWith(BAK_SUFFIX)) continue; + const original = fp.slice(0, -BAK_SUFFIX.length); + if (!shouldRestoreOriginal(original, fp)) continue; + try { + fs.copyFileSync(fp, original); + restored.push(original); + } catch { + /* 文件被占用时下次启动再试 */ + } + } + }; + for (const root of roots) visit(root, 0); + return restored; +} + +export function restoreMissingOriginalsAllHosts() { + const restored = []; + for (const aiBase of enumeratePatchAiBases()) { + try { + restored.push(...restoreMissingOriginalsFromBak(aiBase)); + } catch { + /* 一个宿主失败不挡住其余 */ + } + } + return restored; +} + export async function backupAll(aiBase) { const files = targetFiles(aiBase); const made = []; @@ -5217,6 +5401,7 @@ async function sameFileBytes(left, right) { } export async function revertAll(aiBase, options = {}) { + restoreMissingOriginalsFromBak(aiBase); const files = targetFiles(aiBase); const reverted = []; const skipped = []; @@ -5518,6 +5703,9 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { "agent-loop": allExisting([ ...nestedPkg(aiBase, "dsh-agent-loop", "lib", "index.js"), ]), + "app-boot": allExisting([ + ...nestedPkg(aiBase, "dsh-app-boot", "lib", "index.js"), + ]), "conversation-client": allExisting([ ...nestedPkg(aiBase, "dsh-client-ui-conversation", "lib", "client.js"), ]), @@ -5850,6 +6038,20 @@ function fileKeysOf(p) { return Array.isArray(p.file) ? p.file : [p.file]; } +export function hookDenyPaths(aiBase) { + const files = targetFiles(aiBase); + const out = []; + for (const p of ALL_PATCHES) { + if (!hooksDeny.HOOK_DENY_PATCH_IDS.includes(p.id)) continue; + for (const key of fileKeysOf(p)) { + for (const fp of pathsOf(files, key)) { + if (fp && !out.includes(fp)) out.push(fp); + } + } + } + return out; +} + function patchReplacements(p) { if (Array.isArray(p.replacements)) return p.replacements; return (p.patterns ?? []).map((pat) => ({ pattern: pat, replace: p.replace })); @@ -5937,7 +6139,9 @@ export function applyReplacementsToText(text, patch, fp = "") { } const needle = asLf(pattern); if (!out.includes(needle)) continue; - out = out.split(needle).join(written); + const next = out.split(needle).join(written); + if (next === out) continue; + out = next; changed = true; } if (crlf) out = out.replace(/\n/g, "\r\n"); @@ -5956,7 +6160,7 @@ function rollupPatchStatus({ applied, already, missing, notFound, lastError, key return "pattern_not_found"; } -const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "skipped", "na"]); +const ALWAYS_SOFT_STATUSES = new Set(["applied", "already", "missing_file", "skipped", "na", "off"]); export function patchAppliesHere(patch, surface = detectSurface()) { const want = patch?.surfaces; @@ -6009,6 +6213,48 @@ async function saveText(p, text) { return true; } +export const hookDenyIo = { + hookDenyPaths, + loadText, + saveText, +}; + +let hooksDenySettings = null; +let hooksDenyConfigValue; + +export function setHooksDenyConfigValue(value) { + hooksDenyConfigValue = value; +} + +export function refreshHooksDenySettings() { + hooksDenySettings = Object.freeze( + hooksDeny.loadHookDenySettings(findDshHome(), hooksDenyConfigValue), + ); + return hooksDenySettings; +} + +export function getHooksDenySettings() { + if (!hooksDenySettings) return refreshHooksDenySettings(); + return hooksDenySettings; +} + +export function setHooksDenySettings(patch) { + const saved = hooksDeny.saveHookDenySettings(findDshHome(), patch); + hooksDenySettings = Object.freeze({ hooksDenyBypass: saved.hooksDenyBypass }); + return saved; +} + +export async function restoreHookDenyForBases(bases) { + const failed = []; + const changed = []; + for (const aiBase of bases || []) { + const r = await hooksDeny.restoreHookDenyOfficial(aiBase, hookDenyIo); + changed.push(...r.changed); + failed.push(...r.sentinelLeft, ...r.misses); + } + return { changed, failed }; +} + async function repairPluginCordisYaml() { const fp = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "cordis.patch.yml"); if (!isFile(fp)) return; @@ -6018,6 +6264,7 @@ async function repairPluginCordisYaml() { } export async function applyPatches(aiBase, patches = ALL_PATCHES, options = {}) { + restoreMissingOriginalsFromBak(aiBase); const files = targetFiles(aiBase); const report = []; const preserveClientBundles = options.preserveClientBundles === true; @@ -6180,6 +6427,7 @@ export async function patchStatus(aiBase, patches = ALL_PATCHES) { else if (skipped > 0) status[p.id] = "skipped"; else status[p.id] = p.optional ? "na" : "missing_file"; } + await hooksDeny.annotateHookDenyStatus(status, getHooksDenySettings(), aiBase, hookDenyIo); return status; } @@ -6790,7 +7038,7 @@ export function editOverride(dshHome) { /** 列表上的“已就绪”:已写入、或当前版本不需要 / 组件未装(与 apply 的 soft-ok 对齐)。 */ export function patchStatusReady(status, patch = null) { - if (status === "applied" || status === "already") return true; + if (status === "applied" || status === "already" || status === "off") return true; if (status === "skipped" || status === "missing_file") return true; if (status === "na") return false; if (status === "pattern_not_found" && patch?.strictFiles) return false; @@ -6825,7 +7073,7 @@ export async function gatherState() { patches_total += 1; if (s === "applied") patches_applied += 1; if (s === "pending") patches_pending += 1; - if (s === "skipped" || s === "missing_file") patches_skipped += 1; + if (s === "skipped" || s === "missing_file" || s === "off") patches_skipped += 1; if (patchStatusReady(s, p)) patches_ready += 1; } let shim_cmd = "missing"; @@ -6868,5 +7116,6 @@ export async function gatherState() { override_path: findOverrideFile(dshHome), override_status: await overrideStatus(dshHome), asar_still_sealed: desktopAsarStillSealed(), + hooks_deny_bypass: getHooksDenySettings().hooksDenyBypass, }; } diff --git a/lib/hooks-deny.js b/lib/hooks-deny.js new file mode 100644 index 0000000..20f0daf --- /dev/null +++ b/lib/hooks-deny.js @@ -0,0 +1,217 @@ +// #80:hooks deny / ask 旁路的开关、反向写回官方形态、状态标注。 +// 本模块不 import core.js(core 在需要时回调本模块,避免循环依赖)。 +import fs from "node:fs"; +import path from "node:path"; + +/** #80 产品语义:这四条永远同开关,不拆开。 */ +export const HOOK_DENY_PATCH_IDS = Object.freeze([30, 31, 64, 65]); + +const DEFAULT_SETTINGS = Object.freeze({ hooksDenyBypass: true }); +const SETTINGS_FILE = "hooks-deny.json"; + +/** 补丁 30/31 写出的死字符串;它出现即代表「旁路还开着」。 */ +const DISABLED_SENTINEL = "__dsh_purge_deny_disabled__"; + +const MARKER_STOP = "[dsh-purge] Stop hook steer disabled"; +const MARKER_SUBMIT = "[dsh-purge] UserPromptSubmit deny→allow"; + +/** + * 反向替换表。find 必须逐字命中本插件写出的形态。 + * R1a 活文件(30+65 同一轮):65 把 reject 行写成 `=== "deny"` 空壳。 + * R1a2 二次应用:30 没有 skipIfMarked,会再把空壳里的 `"deny"` 改成死字符串。 + * R1b:只打了 30、还没打 65。 + * R2a / R2b 必须连 body 的 kind 一起匹配,不能只认行首。 + */ +const REVERSES = Object.freeze([ + { + id: "R1a", + find: + '\t\tif (merged.decision === "deny") { /* [dsh-purge] UserPromptSubmit deny→allow */ }\n' + + '\t\telse if (merged.decision === "__dsh_purge_deny_disabled__") { /* [dsh-purge] pre-step reject disabled */ }', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, + { + id: "R1a2", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */' + + ' { /* [dsh-purge] UserPromptSubmit deny→allow */ }\n' + + '\t\telse if (merged.decision === "__dsh_purge_deny_disabled__") { /* [dsh-purge] pre-step reject disabled */ }', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, + { + id: "R1b", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ return { kind: "reject" };', + replace: '\t\tif (merged.decision === "deny") return { kind: "reject" };', + }, + { + id: "R2a", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ return {\n' + + '\t\t\tkind: "deny",', + replace: '\t\tif (merged.decision === "deny") return {\n\t\t\tkind: "deny",', + }, + { + id: "R2b", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ return {\n' + + '\t\t\tkind: "block",', + replace: '\t\tif (merged.decision === "deny") return {\n\t\t\tkind: "block",', + }, + { + id: "R3", + find: '\t\tif (merged.decision === "ask") return next(); /* [dsh-purge] hooks ask→allow */', + replace: + '\t\tif (merged.decision === "ask") return {\n' + + '\t\t\tkind: "ask",\n' + + '\t\t\t...merged.reason !== void 0 ? { reason: merged.reason } : {}\n' + + '\t\t};', + }, + { + id: "R5a", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ {\n' + + '\t\t\treturn; // [dsh-purge] Stop hook steer disabled\n', + replace: '\t\tif (merged.decision === "deny") {\n', + }, + { + id: "R5b", + find: + '\t\tif (merged.decision === "__dsh_purge_deny_disabled__") /* [dsh-purge] hooks deny→allow */ {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";', + replace: + '\t\tif (merged.decision === "deny") {\n' + + '\t\t\tconst text = merged.reason ?? "continue: blocked by Stop hook";', + }, +]); + +const SENTINEL_RULE = Object.freeze({ + id: "R0", + find: '"__dsh_purge_deny_disabled__"', + replace: '"deny"', +}); + +export function applyHookDenyReverses(text) { + let out = String(text || ""); + const hits = []; + for (const rule of REVERSES) { + if (!out.includes(rule.find)) continue; + out = out.split(rule.find).join(rule.replace); + hits.push(rule.id); + } + if (hits.length === 0 && out.includes(DISABLED_SENTINEL)) { + const next = out.split(SENTINEL_RULE.find).join(SENTINEL_RULE.replace); + if (next !== out) { + out = next; + hits.push("R0"); + } + } + return { text: out, hits }; +} + +export function hookFileLooksBypassed(text) { + const hay = String(text || ""); + return hay.includes(DISABLED_SENTINEL) || hay.includes(MARKER_STOP) || hay.includes(MARKER_SUBMIT); +} + +/** + * 把 aiBase 上这四条补丁涉及的文件写回官方形态。 + * @returns {{ files: string[], changed: string[], misses: string[], sentinelLeft: string[], hitsByFile: Record }} + */ +export async function restoreHookDenyOfficial(aiBase, io) { + const result = { files: [], changed: [], misses: [], sentinelLeft: [], hitsByFile: {} }; + if (!aiBase || !io) return result; + const paths = io.hookDenyPaths(aiBase); + for (const fp of paths) { + result.files.push(fp); + let text; + try { + text = await io.loadText(fp); + } catch { + result.misses.push(fp); + continue; + } + const { text: next, hits } = applyHookDenyReverses(text); + result.hitsByFile[fp] = hits; + if (hits.length === 0) { + if (next.includes(DISABLED_SENTINEL)) result.sentinelLeft.push(fp); + continue; + } + try { + const wrote = await io.saveText(fp, next); + if (wrote) result.changed.push(fp); + } catch { + result.misses.push(fp); + } + if (next.includes(DISABLED_SENTINEL)) result.sentinelLeft.push(fp); + } + return result; +} + +export async function annotateHookDenyStatus(status, settings, aiBase, io) { + if (!status || !aiBase || settings?.hooksDenyBypass !== false) return status; + const paths = io.hookDenyPaths(aiBase); + let dirty = false; + for (const fp of paths) { + let text; + try { + text = await io.loadText(fp); + } catch { + continue; + } + if (hookFileLooksBypassed(text)) { + dirty = true; + break; + } + } + for (const id of HOOK_DENY_PATCH_IDS) { + const prev = status[id]; + if (prev === "na" || prev === "missing_file") continue; + status[id] = dirty ? "pending" : "skipped"; + } + return status; +} + +export function hookDenySettingsPath(dshHome) { + return path.join(dshHome, "dsh-purge", SETTINGS_FILE); +} + +export function loadHookDenySettings(dshHome, configValue) { + let file = {}; + try { + const fp = hookDenySettingsPath(dshHome); + if (fs.existsSync(fp)) { + const parsed = JSON.parse(fs.readFileSync(fp, "utf8")); + if (parsed && typeof parsed === "object") file = parsed; + } + } catch { + file = {}; + } + const pick = [file.hooksDenyBypass, configValue, DEFAULT_SETTINGS.hooksDenyBypass]; + const value = pick.find((v) => typeof v === "boolean"); + return { hooksDenyBypass: value === undefined ? true : value }; +} + +export function saveHookDenySettings(dshHome, patch) { + const fp = hookDenySettingsPath(dshHome); + fs.mkdirSync(path.dirname(fp), { recursive: true }); + const current = loadHookDenySettings(dshHome); + const next = { + hooksDenyBypass: typeof patch?.hooksDenyBypass === "boolean" + ? patch.hooksDenyBypass + : current.hooksDenyBypass, + }; + const tmp = `${fp}.${process.pid}.tmp`; + fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, "utf8"); + try { + if (fs.existsSync(fp)) fs.unlinkSync(fp); + } catch { /* rename 覆盖 */ } + fs.renameSync(tmp, fp); + return { ok: true, ...next, path: fp }; +} + +export function selectPatches(patches, settings) { + if (settings?.hooksDenyBypass !== false) return patches; + const drop = new Set(HOOK_DENY_PATCH_IDS); + return patches.filter((p) => !drop.has(p.id)); +} diff --git a/lib/identity.js b/lib/identity.js index 150946f..cfceae4 100644 --- a/lib/identity.js +++ b/lib/identity.js @@ -729,6 +729,23 @@ export function rewritePromptAssembly(assembled, fallbackInject = "", options = : withOps; } assembled.sections = sanitizeAssemblySections(leadWithInject(sections, injectText, protocol)); + if (injectText) { + const needle = injectText.slice(0, 80); + const has = assembled.sections.some((section) => ( + typeof section?.text === "string" && needle && section.text.includes(needle) + )); + if (!has) { + assembled.sections = [ + { + name: "dsh-purge", + text: injectText, + interpolate: false, + order: GLOBAL_PROMPT_ORDER + 1, + }, + ...assembled.sections.filter((section) => section && section.name !== "dsh-purge"), + ]; + } + } if (!Array.isArray(assembled.contexts)) assembled.contexts = []; if (!Array.isArray(assembled.tools)) assembled.tools = []; return assembled; diff --git a/lib/index.js b/lib/index.js index 17cdefb..7ce553c 100644 --- a/lib/index.js +++ b/lib/index.js @@ -58,6 +58,7 @@ const DEFAULTS = { refusalRecoverText: "", // Codex 风格:教模型主动发现 skill / MCP;不改官方注册与工具面。 capabilityProtocol: true, + hooksDenyBypass: true, }; const log = (config, ...args) => { @@ -162,11 +163,26 @@ function injectAllowedNow(config) { /** 提示词框自改 > prompt-inject.md > 加密默认(见 rules.resolveInjectText)。 */ function refreshHungOperator(dshHome = core.findDshHome()) { - const home = dshHome || core.findDshHome(); + const home = core.pinDshHome() || dshHome || core.findDshHome(); try { core.syncPromptInjectOnDiskSync(home); } catch { /* 同步失败仍按 resolve 走 */ } const resolved = rules.resolveInjectText(home); - core.hangOperatorPrompt(resolved.text); - return resolved; + const text = resolved.text || core.normalizeOverride(core.defaultOverrideText()) || ""; + if (text) { + core.hangOperatorPrompt(text); + // 与点「保存」同一钉钉:不点保存,组装也要读到这一份全文。 + core.rememberCommittedOverride(home, text); + } + return { ...resolved, text: text || resolved.text }; +} + +function installHungPromptGlobal() { + globalThis.__dshPurgeHungPrompt = () => { + try { + return refreshHungOperator(core.findDshHome()).text || ""; + } catch { + return core.hungOperatorPrompt() || ""; + } + }; } function injectSnapshot(dshHome = core.findDshHome()) { @@ -269,7 +285,7 @@ export function registerPromptSections(ctx, config, _injectFile) { function readInjectFallback(context) { let home = ""; try { home = core.findDshHome(); } catch { home = ""; } - const raw = rules.ensureOperatorBody(home); + const raw = refreshHungOperator(home).text || rules.ensureOperatorBody(home); if (!raw) return ""; let redteam = false; try { redteam = isRedteamSession(context); } catch { redteam = false; } @@ -418,7 +434,7 @@ function installIdentityOverride(ctx, config = {}) { // 切换预设会换掉 assemble。pre-step 瀑布在 assemble 之后才跑,第一次发送包不上。 // 宿主在 assemble 之前调用这个函数,用的就是当前模式自己的 systemPrompt。 const prepareAssemble = (loopCtx) => { - try { rules.ensureOperatorBody(core.findDshHome()); } catch { /* 主目录还没有提示词 */ } + try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ } const prompt = loopCtx && loopCtx.systemPrompt; if (prompt) { try { @@ -428,8 +444,10 @@ function installIdentityOverride(ctx, config = {}) { } catch { /* 这一层代理包不上时,下面再包插件自己的 */ } } wrapAssemble(); + return prompt || null; }; globalThis.__dshPurgePrepareAssemble = prepareAssemble; + installHungPromptGlobal(); // complete:true 会在 waterfall 之后盖掉 sections;包住 assemble 返回值,每轮都补回注入。 wrapAssemble(); const started = Date.now(); @@ -442,7 +460,7 @@ function installIdentityOverride(ctx, config = {}) { try { ctx.on("session/created", wrapAssemble); } catch { /* ignore */ } try { ctx.on("agent-preset/selected", () => { - try { rules.ensureOperatorBody(core.findDshHome()); } catch { /* 主目录还没有提示词 */ } + try { refreshHungOperator(core.findDshHome()); } catch { /* 主目录还没有提示词 */ } wrapAssemble(); }, { global: true }); } catch { /* ignore */ } @@ -581,6 +599,14 @@ async function autoApply(config) { const sanitized = core.sanitizeDesktopCommandRuntimes(); if (sanitized.length) log(config, "desktop runtime sanitized:", JSON.stringify(sanitized)); + core.refreshHooksDenySettings(); + if (core.getHooksDenySettings().hooksDenyBypass === false) { + const restored = await core.restoreHookDenyForBases(core.enumeratePatchAiBases()); + if (restored.failed.length) { + log(config, "hooks-deny restore leftover:", restored.failed.join(",")); + } + } + const state = await core.gatherState(); if (!state.ai_base) { log(config, "skip auto-apply: plugin root not found"); @@ -696,7 +722,8 @@ async function handlePurgeCommand(rawInput, config) { lines.push("Desktop: host-commands 密封目录只清理不注入;bak 禁止写进 bin(issue #9)。"); const summary = core.summarizeApplyReport(report); const hostWritten = core.allPatchHostsWritten(applyMulti.hosts) || core.hostCleanMarkersPresent(state.ai_base); - const complete = summary.failed.length === 0 && flash.ok === true && hostWritten; + const hookDenyRestoreFailed = (applyMulti.hookDenyRestoreFailed || []).length > 0; + const complete = summary.failed.length === 0 && flash.ok === true && hostWritten && !hookDenyRestoreFailed; const promptReady = summary.failed.length > 0 && summary.failed.every((item) => item.status === "pattern_not_found"); const shouldRestart = applyShouldRestart({ complete: complete || (promptReady && hostWritten), @@ -1004,6 +1031,19 @@ async function handleSkillsCommand(rawInput) { export function apply(ctx, config) { const cfg = { ...DEFAULTS, ...(config || {}) }; if (!cfg.enabled) return; + core.setHooksDenyConfigValue(cfg.hooksDenyBypass); + core.refreshHooksDenySettings(); + try { + const home = core.pinDshHome() || core.findDshHome(); + installHungPromptGlobal(); + refreshHungOperator(home); + } catch { /* 主目录还没有时,组装会再挂内置默认 */ } + try { + const restored = core.restoreMissingOriginalsAllHosts(); + if (restored.length) log(cfg, "restored missing overlay from bak:", restored.join(",")); + } catch (e) { + console.warn("[dsh-purge] restore bak:", String(e && e.message ? e.message : e)); + } const life = watchContextLife(ctx); if (!life.alive) { console.warn("[dsh-purge] skip apply: inactive context"); @@ -1080,7 +1120,7 @@ export function apply(ctx, config) { function applyHostHooks(ctx, cfg) { try { const home = core.pinDshHome() || core.findDshHome(); - rules.ensureOperatorBody(home); + refreshHungOperator(home); } catch { /* 主目录尚未就绪 */ } installIdentityOverride(ctx, cfg); installRegionGate(ctx); @@ -1349,6 +1389,7 @@ function installWebServer(ctx, cfg) { boot_full_quit: bootFullQuit, update: updater.lastUpdateResult(), ...updater.channelPublic(), + hooks_deny_bypass: core.getHooksDenySettings().hooksDenyBypass, ...(await skills.skillsStatus(core.findDshHome()).catch(() => ({ skills: [] }))), }); } catch (e) { @@ -1356,6 +1397,37 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: status"); + registerPluginRoute({ + kind: "exact", + path: "/dsh-purge/hooks-deny", + handler: async (request, response) => { + if (request.method === "GET") { + try { + const settings = core.refreshHooksDenySettings(); + sendJson(response, 200, { ok: true, hooksDenyBypass: settings.hooksDenyBypass }); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e) }); + } + return; + } + if (request.method === "POST") { + try { + const body = await readJsonBody(request); + if (typeof body?.hooksDenyBypass !== "boolean") { + sendJson(response, 400, { ok: false, error: "hooksDenyBypass must be boolean" }); + return; + } + const saved = core.setHooksDenySettings({ hooksDenyBypass: body.hooksDenyBypass }); + sendJson(response, 200, { ok: true, hooksDenyBypass: saved.hooksDenyBypass }); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e) }); + } + return; + } + response.writeHead(405, { allow: "GET, POST" }); + response.end(); + }, + }, "dsh-purge: hooks-deny"); registerPluginRoute({ kind: "exact", path: "/dsh-purge/last-user", @@ -1511,7 +1583,7 @@ function installWebServer(ctx, cfg) { }); return; } - if (incoming !== null) { + if (typeof incoming === "string" && core.normalizeOverride(incoming)) { await core.saveOverrideContent(state.dsh_home, incoming); } const httpMulti = await core.applyPatchesAllHosts(core.ALL_PATCHES, { @@ -1530,7 +1602,8 @@ function installWebServer(ctx, cfg) { const summary = core.summarizeApplyReport(report); const hostWritten = core.allPatchHostsWritten(httpMulti.hosts) || core.hostCleanMarkersPresent(state.ai_base); - const complete = summary.failed.length === 0 && flash.ok === true && hostWritten; + const hookDenyRestoreFailed = (httpMulti.hookDenyRestoreFailed || []).length > 0; + const complete = summary.failed.length === 0 && flash.ok === true && hostWritten && !hookDenyRestoreFailed; const sealedNow = core.desktopAsarStillSealed(); const promptReady = summary.failed.length > 0 && summary.failed.every((item) => item.status === "pattern_not_found"); if (flash.ok === true && (complete || promptReady) && hostWritten) { diff --git a/lib/redteam/store-core.js b/lib/redteam/store-core.js index 9f04cc0..3edce74 100644 --- a/lib/redteam/store-core.js +++ b/lib/redteam/store-core.js @@ -299,6 +299,39 @@ export const POINT_STAGE_OVERRIDE = { 'boundary-physical': 'boundary', 'boundary-supply': 'boundary', } +/** + * 得分点的短名:报告正文、索引表、链路表用它。 + * 合并后的得分点全名太长,放不进表头;全名仍写在每条明细的「得分点」一行。 + */ +export const POINT_SHORT_NAME = { + 'domain-control': '域名控制', + 'terminal-access': '终端权限', + 'server-host': '服务器主机', + 'db-credential': '数据库凭据', + 'web-app': 'Web 应用', + 'central-system': '集权系统', + 'bigdata-system': '大数据系统', + 'netdev': '网络设备', + 'netdev-redirect': '网络重定向', + 'netdev-implant': '网络设备植入', + 'iiot': '工业互联网', + 'cloud-platform': '云管理平台', + 'iot-platform': '物联网平台', + 'secdev': '安全设备', + 'file-storage': '文件存储', + 'ai-agent': '模型智能体', + 'model-compute': '算力 / 知识库系统', + 'model-data': '模型数据系统', + 'computepower-admin': '算力基础设施', + 'computepower-cards': '算力卡资源', + 'boundary-logical': '进入逻辑隔离内网', + 'boundary-strong': '进入强隔离内网', + 'boundary-physical': '进入物理隔离内网', + 'boundary-supply': '供应链 / 云服务通道', + 'iot-corenet': '物联网打入核心网', + 'core-system': '核心系统(旧口径)', +} + /** * 自动推导一条得分属于哪个阶段(用户已确认:自动推导,允许显式覆盖): * ① 显式 stage_code 优先 diff --git a/lib/refusal-recover.js b/lib/refusal-recover.js index 1425b0e..be737ae 100644 --- a/lib/refusal-recover.js +++ b/lib/refusal-recover.js @@ -39,8 +39,7 @@ export function makeRecoverMessage(text) { role: "user", content: [{ type: "text", text: body }], source: { - kind: "plugin", - plugin: "dsh-purge", + kind: "dsh-purge", form: "notice", summary: "refusal-recover", }, diff --git a/package.json b/package.json index b9ea0cb..01f64d1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.65", + "version": "1.1.66", "description": "DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model — swap prompts per model. 求 Star 收藏 ⭐ 如要二开,请查看署名要求部分", "type": "module", "main": "lib/index.js", diff --git a/release-notes.md b/release-notes.md index 67eb2e7..9ec3aef 100644 --- a/release-notes.md +++ b/release-notes.md @@ -1,3 +1,23 @@ +# 1.1.66 + +## 中文 + +- 版本 **1.1.66**。 +- **#80**:清洗页可关掉 hooks deny / ask 旁路。关掉且文件干净显示跳过,不计入已应用;关掉后再打开,64/65 会按官方形态再打一次。 +- **#81**:继续 / 拒答续跑的来源 kind 改为 `dsh-purge`;限流和传输失败不再自动续一轮。 +- 重启后不用点保存也会挂上默认提示词;每一轮都补回全文。空的应用请求不再清空磁盘上的提示词。 +- 声明过的 overlay 只剩 `.dshpurge.bak` 时,应用会先拷回再加载。 +- 红队报告补上得分点短名。中文 README 恢复题图和预览图。 + +## English + +- **1.1.66**. +- **#80**: The clean page can turn off the hooks deny/ask bypass. Off + clean files show skipped and are not counted as applied. Turning it back on reapplies 64/65 from the official form. +- **#81**: Continue / refusal-recover use source kind `dsh-purge`. RATE_LIMIT and TRANSPORT no longer start another continue turn. +- Restart hangs the default prompt without a Save click; every step puts the full text back. An empty Apply body no longer wipes the disk prompt. +- A declared overlay that exists only as `.dshpurge.bak` is copied back before load. +- Red-team reports get short score-point names. Chinese README restores the banner and preview images. + # 1.1.65 ## 中文