From ea2632cd757eef6824c17c9c96f343f24e782698 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: Fri, 18 Sep 2026 10:54:43 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E5=B8=83=201.1.2=EF=BC=8C?= =?UTF-8?q?=E5=85=BC=E5=AE=B9=E6=8E=A5=E5=8F=A3=20developer=20=E8=A7=92?= =?UTF-8?q?=E8=89=B2=E4=B8=8E=E8=A7=84=E5=88=99=E9=9B=86=E8=AF=BB=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- README.md | 36 +++----- README.zh-CN.md | 36 +++----- client.js | 27 ++++-- lib/core.js | 83 +++++++++++++++++ lib/index.js | 241 +++++++++++++++++++++++------------------------- package.json | 2 +- 6 files changed, 239 insertions(+), 186 deletions(-) diff --git a/README.md b/README.md index 62aa29e..e2c8712 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.1

+

Version 1.1.2

DeepSeek Harness jailbreak (破甲): every model can jailbreak; swap prompts per model. Default prompt for Chinese models — 小码酱. Please star ⭐ @@ -167,13 +167,13 @@ If the official DeepSeek Harness desktop client (EXE) is installed, the button b

🌐 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.1&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.zip +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.2&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.zip ``` **Web trigger example:** @@ -186,7 +186,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.1', + version: '1.1.2', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', @@ -205,7 +205,7 @@ export function installDshPurgeToDesktop() { **HTML link:** ```html - + 🚀 Install in desktop client ``` @@ -216,7 +216,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | Plugin id | | name | `dsh-purge` | Display name | -| version | `1.1.1` | Semver | +| version | `1.1.2` | Semver | | repo | `YuJunZhiXue/dsh-purge` | GitHub repo | | permissions | `系统提示词注入, 本机补丁, 设置页` | Requested permissions | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | Zip URL | @@ -537,6 +537,11 @@ If nothing is found, set `DSH_BASE`. No files are changed. ## Changelog +### 1.1.2 + +- Custom OpenAI-compatible APIs no longer 400 on `developer` role: `#42` remaps it back to `system`. +- Settings rule sets: read / delete / save go through one POST so the browser no longer fails with `Failed to fetch`. + ### 1.1.1 - Composer **Undo** / `/rewind`: main agent can rewind once or the last round (drop this round’s subagents); a subagent rewinds once. @@ -556,25 +561,6 @@ If nothing is found, set `DSH_BASE`. No files are changed. - Version numbering reset. - Settings: **Check update** reads GitHub `master`. -### 1.3.6 (dsh 0.1.5-rc.1) - -- **persona schema:** 0.1.5 requires `prefix`; `#39` aliases community `text` so picking a workspace / opening a chat no longer wipes empty. -- **history:** `#40` lets mnemon v0 `summary` migrate when `form` is not `notice`. -- **identity:** no plugin identity card; the `dsh-purge` section is verbatim `prompt-inject.md`. -- **disclaimer:** zero-tolerance, controlled-scope, license-termination, and independence clauses. -- **settings UI:** patch groups now include `#33`–`#40`. - -### 1.3.5 (dsh 0.1.2-rc.1 / Node 24 Windows) - -- **CMD flash:** fix Node 24 ESM `spawn` patch miss; silence subprocess-local / doctor / dshmarket / liangshen bash / doctor stub paths. -- **First-turn inject:** liangshen phase-1 keeps persona + inject. -- **Restart:** `/dsh-purge/restart` uses `node + bin.js` only, waits for the port, never pops cmd. -- **Patch markers:** #21 and friends accept `^0.1.2-rc.1` dependency spellings (fewer false pendings). - -### 1.3.4 - -- Desktop sealed `host-commands/**/bin` is scrub-only — no `dsh.cmd.dshpurge.bak` recovery loops. - ## Notes - Scope is rendered copy, defaults, and runtime logic inside local `@deepseek-ai/*` packages, plus override files and rule sets under the harness home. diff --git a/README.zh-CN.md b/README.zh-CN.md index 91dc867..135b5e1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@

dsh-purge

-

Version 1.1.1

+

Version 1.1.2

DeepSeek Harness 破甲:让所有模型都能破甲,不同模型可换不同提示词。默认提示词面向国模「小码酱」。求 Star 收藏 ⭐ @@ -164,13 +164,13 @@ dsh plugin --profile default remove dsh-purge

🌐 打开插件市场页  ·  - 🚀 唤起客户端一键安装 + 🚀 唤起客户端一键安装

🔗 **原生协议链接:** ``` -dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.1&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.zip +dsh://plugin/install?id=dsh-purge&name=dsh-purge&version=1.1.2&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.zip ``` **网页端(前端)触发代码示例:** @@ -183,7 +183,7 @@ export function installDshPurgeToDesktop() { const params = new URLSearchParams({ id: 'dsh-purge', name: 'dsh-purge', - version: '1.1.1', + version: '1.1.2', repo: 'YuJunZhiXue/dsh-purge', permissions: '系统提示词注入, 本机补丁, 设置页', downloadUrl: 'https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip', @@ -202,7 +202,7 @@ export function installDshPurgeToDesktop() { **HTML 静态链接方式:** ```html - + 🚀 唤起客户端一键安装 ``` @@ -213,7 +213,7 @@ export function installDshPurgeToDesktop() { |---|---|---| | id | `dsh-purge` | 插件唯一标识符 | | name | `dsh-purge` | 插件展示名称 | -| version | `1.1.1` | 语义化版本号 | +| version | `1.1.2` | 语义化版本号 | | repo | `YuJunZhiXue/dsh-purge` | GitHub 仓库 | | permissions | `系统提示词注入, 本机补丁, 设置页` | 申请权限 | | downloadUrl | `https://github.com/YuJunZhiXue/dsh-purge/archive/refs/heads/master.zip` | zip 下载直链 | @@ -541,6 +541,11 @@ npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑 ## 更新记录 +### 1.1.2 + +- 自定义 OpenAI 兼容接口不再因 `developer` 角色 400:`#42` 改回 `system`。 +- 设置页规则集:读 / 删 / 存走同一个 POST,不再报 `Failed to fetch`。 + ### 1.1.1 - 输入框旁「回退」/ `/rewind`:主代理可选回退一次或上一轮(丢掉本轮子代理);子代理直接回退一次。 @@ -560,25 +565,6 @@ npm 嵌套布局下,审批在 `dsh-user-approval/lib/index.js`,升级逻辑 - 版本号从头计数。 - 设置页增加 **检测更新**:对照 GitHub `master`。 -### 1.3.6(适配 dsh 0.1.5-rc.1) - -- **persona schema**:0.1.5 只要 `prefix`;`#39` 把社区预设的 `text` 收成别名,选工作区 / 开新对话不再被清空。 -- **历史会话**:`#40` 放行 mnemon 的 v0 `summary`(`form` 不是 `notice` 也能过迁移)。 -- **身份**:取消插件身份卡;`dsh-purge` 段只贴 `prompt-inject.md`。 -- **声明**:补全零容忍、受控范围、违约终止授权与第三方独立性条款。 -- **设置页**:补丁分组补上 `#33`–`#40`。 - -### 1.3.5(适配 dsh 0.1.2-rc.1 / Node 24 Windows) - -- **CMD 闪窗**:修复 Node 24 ESM `spawn` 补丁无效;subprocess-local / doctor / dshmarket / 梁神 bash / doctor stub 全路径无感。 -- **首轮注入**:梁神 phase-1 保留 persona 与 inject。 -- **重启**:`/dsh-purge/restart` 只走 `node + bin.js`,等待端口释放后再拉起,不弹 cmd。 -- **补丁标记**:#21 等兼容 `^0.1.2-rc.1` 依赖写法,减少假 pending。 - -### 1.3.4 - -- Desktop 密封 `host-commands/**/bin` 只清理不注入,避免 `dsh.cmd.dshpurge.bak` 触发恢复模式。 - ## 说明 - 改动范围是本机 `@deepseek-ai/*` 包里的渲染文案、默认策略和执行逻辑,以及用户目录下的覆盖文件与规则集。 diff --git a/client.js b/client.js index de75ff9..7187d89 100644 --- a/client.js +++ b/client.js @@ -41,10 +41,22 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { return data; } catch (e) { if (isAbortError(e)) throw new Error("timeout"); + const msg = String((e && e.message) || e || ""); + if (/failed to fetch|networkerror|load failed/i.test(msg)) { + throw new Error("连不上接口,请确认 dsh 还在跑后 Ctrl+F5"); + } throw e; } finally { clearTimeout(timer); } } + function rulesApi(op, extra) { + return apiJson("/dsh-purge/rules", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(Object.assign({ op: op }, extra || {})), + }); + } + const TARGETS = ["AGENTS.md", "CLAUDE.md"]; const PATCH_GROUPS = [ { key: "prompt", ids: [1, 2, 3, 4, 5, 26, 27, 28, 29, 33] }, @@ -766,7 +778,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const loadStatus = useCallback(() => { const tr = tRef.current; - apiJson("/dsh-purge/rules/status") + rulesApi("status") .then((d) => { if (d && d.ok) setSt(d); else { @@ -785,19 +797,14 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const doPost = useCallback((action, payload, after) => { setBusy(true); setNotice({ kind: "idle", text: "" }); - fetch("/dsh-purge/rules/" + action, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(payload || {}), - }) - .then((r) => r.json()) + rulesApi(action, payload) .then((d) => { - if (d.ok) { + if (d && d.ok) { setNotice({ kind: "ok", text: t("ok.done") }); loadStatus(); if (after) after(); } else { - setNotice({ kind: "error", text: t("err.action", { error: d.error || "" }) }); + setNotice({ kind: "error", text: t("err.action", { error: (d && d.error) || "" }) }); } }) .catch((e) => setNotice({ kind: "error", text: t("err.action", { error: e.message }) })) @@ -806,7 +813,7 @@ window.__ModuleLoader__.load({ id: "dsh-purge", factory: (require) => { const openRule = useCallback((id) => { setBusy(true); - apiJson("/dsh-purge/rules/read?id=" + encodeURIComponent(id)) + rulesApi("read", { id: id }) .then((d) => { if (d.ok) { setEditId(id); diff --git a/lib/core.js b/lib/core.js index cd855b4..5489e31 100644 --- a/lib/core.js +++ b/lib/core.js @@ -712,6 +712,44 @@ function listMnemonIndexFiles(dshHome) { return out; } +function listPiAiApiFiles(dshHome, aiBase, filename) { + const out = []; + const seen = new Set(); + const push = (fp) => { + if (!fp || !isFile(fp)) return; + let key = fp; + try { key = fs.realpathSync(fp); } catch { /* keep fp */ } + key = String(key).toLowerCase(); + if (seen.has(key)) return; + seen.add(key); + out.push(fp); + }; + const rel = ["@earendil-works", "pi-ai", "dist", "api", filename]; + if (aiBase) { + push(path.join(aiBase, "..", ...rel)); + push(path.join(aiBase, "dsh", "node_modules", ...rel)); + push(path.join(aiBase, "..", "@deepseek-ai", "dsh", "node_modules", ...rel)); + } + for (const home of [dshHome, ...desktopDshHomeGuesses()].filter(Boolean)) { + push(path.join(home, "profiles", "node_modules", ...rel)); + push(path.join(home, "profiles", "node_modules", "@deepseek-ai", "dsh", "node_modules", ...rel)); + const profilesRoot = path.join(home, "profiles"); + if (!isDir(profilesRoot)) continue; + let names = []; + try { + names = fs.readdirSync(profilesRoot, { withFileTypes: true }).filter((d) => d.isDirectory()); + } catch { + names = []; + } + for (const ent of names) { + const base = path.join(profilesRoot, ent.name, "node_modules"); + push(path.join(base, ...rel)); + push(path.join(base, "@deepseek-ai", "dsh", "node_modules", ...rel)); + } + } + return out; +} + // 删 supervisor.cmd/vbs,不要留空文件,否则 doctor 每轮都会 schtasks /Delete。 export function stubDoctorSupervisor() { if (process.platform !== "win32") return { skipped: "not_win32" }; @@ -2781,6 +2819,49 @@ const NEW_TOOL_PATCHES = [ ], markers: ["[dsh-purge] complete prompt keeps inject"], }, + { + // 自定义 OpenAI 兼容接口不认 developer;推理模型默认会把 system 收成这个角色,直接 400。 + id: 42, name: "DEVELOPER_ROLE_TO_SYSTEM", layer: "0.1.5 兼容", layer_en: "0.1.5", + desc: "developer 角色改回 system,兼容接口不再 400 / remap developer role to system", + file: ["pi-ai-completions", "pi-ai-responses-shared"], + optional: true, + skipIfMarked: true, + replacements: [ + { + pattern: + " const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;\n" + + " const role = useDeveloperRole ? \"developer\" : \"system\";", + replace: + " const useDeveloperRole = false; // [dsh-purge] compatible APIs reject developer\n" + + " const role = useDeveloperRole ? \"developer\" : \"system\";", + }, + { + pattern: + " lastRole = msg.role;\n" + + " }\n" + + " return params;\n" + + "}\n" + + "function convertTools(", + replace: + " lastRole = msg.role;\n" + + " }\n" + + " for (const message of params) {\n" + + " if (message && message.role === \"developer\") message.role = \"system\";\n" + + " } // [dsh-purge] compatible APIs reject developer\n" + + " return params;\n" + + "}\n" + + "function convertTools(", + }, + { + pattern: + " const role = model.reasoning && compat?.supportsDeveloperRole !== false ? \"developer\" : \"system\";", + replace: + " const role = \"system\"; // [dsh-purge] compatible APIs reject developer", + }, + ], + markersAny: true, + markers: ["[dsh-purge] compatible APIs reject developer"], + }, ]; export const ALL_PATCHES = [...PATCHES, ...CODE_PATCHES, ...ENGINE_PATCHES, ...NEW_TOOL_PATCHES]; @@ -3101,6 +3182,8 @@ export function targetFiles(aiBase, dshHome = findDshHome()) { "hooks-codex-nested": firstExisting([ path.join(aiBase, "dsh", "node_modules", "@deepseek-ai", "dsh-hooks-codex", "lib", "index.js"), ]), + "pi-ai-completions": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-completions.js")), + "pi-ai-responses-shared": allExisting(listPiAiApiFiles(dshHome, aiBase, "openai-responses-shared.js")), }; } diff --git a/lib/index.js b/lib/index.js index 7a8932a..6d7d79a 100644 --- a/lib/index.js +++ b/lib/index.js @@ -951,141 +951,130 @@ function methodNotAllowed(request, response, allow) { return true; } -function installRulesHttp(webServer) { +async function handleRulesOp(op, body, queryId) { const dshHome = core.findDshHome(); - - webServer.register({ - kind: "exact", - path: "/dsh-purge/rules/status", - handler: async (request, response) => { - if (methodNotAllowed(request, response, ["GET"])) return; - try { - sendJson(response, 200, { ok: true, ...(await rules.rulesStatus(dshHome)) }); - } catch (e) { - sendJson(response, 500, { ok: false, error: String(e) }); - } - }, - }, "dsh-purge: rules status"); - - webServer.register({ - kind: "exact", - path: "/dsh-purge/rules/read", - handler: async (request, response) => { - if (methodNotAllowed(request, response, ["GET"])) return; - try { - const url = new URL(request.url ?? "", "http://localhost"); - const id = url.searchParams.get("id") ?? ""; - if (!rules.validRuleId(id)) { - sendJson(response, 400, { ok: false, error: "invalid id" }); - return; - } - const content = await rules.readRule(dshHome, id); - if (content === null) { - sendJson(response, 404, { ok: false, error: `rule not found: ${id}` }); - return; - } - const meta = await rules.readRuleMeta(dshHome, id); - sendJson(response, 200, { ok: true, id, name: meta.name, target: meta.target, content }); - } catch (e) { - sendJson(response, 500, { ok: false, error: String(e) }); - } - }, - }, "dsh-purge: rules read"); - - webServer.register({ - kind: "exact", - path: "/dsh-purge/rules/save", - handler: async (request, response) => { - if (methodNotAllowed(request, response, ["POST"])) return; - try { - const body = await readJsonBody(request); - const id = typeof body?.id === "string" ? body.id : ""; - const content = typeof body?.content === "string" ? body.content : null; - if (!rules.validRuleId(id) || content === null) { - sendJson(response, 400, { ok: false, error: "id and content (string) required" }); - return; - } - await rules.saveRule(dshHome, id, content, { - name: typeof body?.name === "string" ? body.name : undefined, - target: typeof body?.target === "string" ? body.target : undefined, - }); - sendJson(response, 200, { ok: true, id }); - } catch (e) { - sendJson(response, 500, { ok: false, error: String(e) }); - } - }, - }, "dsh-purge: rules save"); - - webServer.register({ - kind: "exact", - path: "/dsh-purge/rules/activate", - handler: async (request, response) => { - if (methodNotAllowed(request, response, ["POST"])) return; - try { - const body = await readJsonBody(request); - const id = typeof body?.id === "string" ? body.id : ""; - if (!rules.validRuleId(id)) { - sendJson(response, 400, { ok: false, error: "invalid id" }); - return; - } - const meta = await rules.activateRule(dshHome, id); - sendJson(response, 200, { - ok: true, - id, - name: meta.name, - target: meta.target, - agents_path: rules.targetPath(dshHome, meta.target), - note: "已写入目标文件并注入 systemPrompt,新会话生效", - }); - } catch (e) { - sendJson(response, 500, { ok: false, error: String(e) }); - } - }, - }, "dsh-purge: rules activate"); - - webServer.register({ - kind: "exact", - path: "/dsh-purge/rules/delete", - handler: async (request, response) => { - if (methodNotAllowed(request, response, ["POST"])) return; - try { - const body = await readJsonBody(request); - const id = typeof body?.id === "string" ? body.id : ""; - if (!rules.validRuleId(id)) { - sendJson(response, 400, { ok: false, error: "invalid id" }); - return; - } - await rules.deleteRule(dshHome, id); - sendJson(response, 200, { ok: true, id }); - } catch (e) { - sendJson(response, 500, { ok: false, error: String(e) }); - } - }, - }, "dsh-purge: rules delete"); - - webServer.register({ - kind: "exact", - path: "/dsh-purge/rules/reset", - handler: async (request, response) => { - if (methodNotAllowed(request, response, ["POST"])) return; - try { - const r = await rules.resetToOriginal(dshHome); - sendJson(response, 200, { ok: true, ...r, note: "已还原出厂状态(无全局指令);规则库保留" }); - } catch (e) { - sendJson(response, 500, { ok: false, error: String(e) }); - } - }, - }, "dsh-purge: rules reset"); + const id = typeof body?.id === "string" ? body.id : String(queryId || ""); + if (op === "status") { + return { ok: true, ...(await rules.rulesStatus(dshHome)) }; + } + if (op === "read") { + if (!rules.validRuleId(id)) return { status: 400, ok: false, error: "invalid id" }; + const content = await rules.readRule(dshHome, id); + if (content === null) return { status: 404, ok: false, error: `rule not found: ${id}` }; + const meta = await rules.readRuleMeta(dshHome, id); + return { ok: true, id, name: meta.name, target: meta.target, content }; + } + if (op === "save") { + const content = typeof body?.content === "string" ? body.content : null; + if (!rules.validRuleId(id) || content === null) { + return { status: 400, ok: false, error: "id and content (string) required" }; + } + await rules.saveRule(dshHome, id, content, { + name: typeof body?.name === "string" ? body.name : undefined, + target: typeof body?.target === "string" ? body.target : undefined, + }); + return { ok: true, id }; + } + if (op === "activate") { + if (!rules.validRuleId(id)) return { status: 400, ok: false, error: "invalid id" }; + const meta = await rules.activateRule(dshHome, id); + return { + ok: true, + id, + name: meta.name, + target: meta.target, + agents_path: rules.targetPath(dshHome, meta.target), + note: "已写入目标文件并注入 systemPrompt,新会话生效", + }; + } + if (op === "delete") { + if (!rules.validRuleId(id)) return { status: 400, ok: false, error: "invalid id" }; + await rules.deleteRule(dshHome, id); + return { ok: true, id }; + } + if (op === "reset") { + const r = await rules.resetToOriginal(dshHome); + return { ok: true, ...r, note: "已还原出厂状态(无全局指令);规则库保留" }; + } + return { status: 400, ok: false, error: `unknown op: ${op}` }; } +function rulesHttpHandler(forcedOp) { + return async (request, response) => { + if (request.method === "OPTIONS") { + sendOptions(response); + return; + } + try { + const url = new URL(request.url ?? "", "http://127.0.0.1"); + const tail = url.pathname.replace(/^\/dsh-purge\/rules\/?/, "").replace(/\/$/, ""); + let body = {}; + if (request.method === "POST") body = await readJsonBody(request); + else if (methodNotAllowed(request, response, forcedOp ? ["GET", "POST"] : ["GET", "POST"])) return; + const op = forcedOp || body.op || tail || "status"; + const result = await handleRulesOp(op, body, url.searchParams.get("id")); + sendJson(response, result.status || 200, result); + } catch (e) { + sendJson(response, 500, { ok: false, error: String(e && e.message ? e.message : e) }); + } + }; +} + +function installRulesHttp(webServer) { + const stop = []; + stop.push(registerRoute(webServer, { + kind: "exact", + path: "/dsh-purge/rules", + handler: rulesHttpHandler(""), + })); + stop.push(registerRoute(webServer, { + kind: "prefix", + path: "/dsh-purge/rules", + handler: rulesHttpHandler(""), + })); + for (const op of ["status", "read", "save", "activate", "delete", "reset"]) { + stop.push(registerRoute(webServer, { + kind: "exact", + path: `/dsh-purge/rules/${op}`, + handler: rulesHttpHandler(op), + })); + } + return () => { + for (let i = stop.length - 1; i >= 0; i -= 1) { + try { stop[i]?.(); } catch { /* ignore */ } + } + }; +} + +const CORS_HEAD = { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "content-type", +}; + function sendJson(response, status, payload) { response.writeHead(status, { "cache-control": "no-store", "content-type": "application/json; charset=utf-8", + ...CORS_HEAD, }); response.end(JSON.stringify(payload)); } +function sendOptions(response) { + response.writeHead(204, { ...CORS_HEAD, "access-control-max-age": "86400" }); + response.end(); +} + +function registerRoute(webServer, spec) { + try { + return webServer.register(spec); + } catch (e) { + console.warn("[dsh-purge] route", spec?.path, String(e && e.message ? e.message : e)); + return () => {}; + } +} + async function readJsonBody(request) { const chunks = []; let size = 0; @@ -1095,5 +1084,7 @@ async function readJsonBody(request) { if (size > 512 * 1024) throw new Error("request body too large"); chunks.push(buffer); } - return JSON.parse(Buffer.concat(chunks).toString("utf8")); + const raw = Buffer.concat(chunks).toString("utf8").trim(); + if (!raw) return {}; + return JSON.parse(raw); } diff --git a/package.json b/package.json index 07c7c07..1e24051 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-purge", - "version": "1.1.1", + "version": "1.1.2", "description": "DeepSeek Harness 破甲:所有模型都可破甲,不同模型可换不同提示词;默认提示词面向国模「小码酱」。Jailbreak for every model. 求 Star ⭐", "type": "module", "main": "lib/index.js",