diff --git a/README.md b/README.md index 621ce71..5e65ebd 100644 --- a/README.md +++ b/README.md @@ -752,6 +752,9 @@ If nothing is found, set `DSH_BASE` / `DSH_DESKTOP_INSTALL`. No files are change - Settings splits Stable / Beta into two columns, each with its own list, switch, and rollback. 1.1.10 can reach this by Check update. - **No Skill import.** Skill stays on beta 1.1.12. - **#29:** Stop pinning the previous full system prompt. That pin was meant to stop a new「系统提示词」card each step, but presets that append a section every assemble (梁神 `workspace-instructions`) turned it into “last full prompt + this step’s block”, so the prompt grew every step and prefix cache missed. Later turns only fold `prompt-inject` into persona, and do not fold a second copy when it is already there. +- The version list marks「当前」by commit. An older tag with the same 1.1.11 version is no longer current next to `master`. +- Local routes reject cross-origin requests, and updates only accept a known ref. Another webpage cannot apply, revert, uninstall, or switch. +- Patch #41 no longer keeps the `dsh-purge:committed` shortcut. Hosts that already applied the old patch need one more Apply to remove it. ### 1.1.10 diff --git a/README.zh-CN.md b/README.zh-CN.md index 58de7a0..2630aa1 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -739,6 +739,9 @@ prompt-inject.md 有内容? ──是──> 原样写入 dsh-purge systemPrompt - 设置页把正式版和测试版左右分开,各自选版本、各自切换和回退。还在 1.1.10 的点「检测更新」就能升到这一版。 - **没有 Skill 导入。** Skill 只在测试版 1.1.12。 - **#29:** 去掉「钉住上一条系统提示全文」。起初为了避免每步追加「系统提示词」,把上一轮全文钉回去;和每轮追加 section 的预设(梁神的 `workspace-instructions`)叠在一起后,系统提示每步变长,前缀缓存整段失效。现在每轮只把 `prompt-inject` 折进 persona,已经折过就不再折第二份。 +- 版本列表按提交号标「当前」。同为 1.1.11 的旧标签不再和 `master` 一起显示当前。 +- 本机接口拒绝跨站请求,更新只接受已知版本。任意网页不能再调用应用、还原、卸载或切换。 +- 补丁 #41 去掉 `dsh-purge:committed` 短路。已经打过旧补丁的,再点一次「应用」才会从宿主文件里删掉。 ### 1.1.10 diff --git a/lib/core.js b/lib/core.js index 6f1720c..72a95e3 100644 --- a/lib/core.js +++ b/lib/core.js @@ -2976,8 +2976,6 @@ const NEW_TOOL_PATCHES = [ "\t\t\t...transformed,\n" + "\t\t\tsections: completeSection === void 0 ? transformed.sections : (function (complete, assembled) {\n" + "\t\t\t\tconst sections = assembled.sections || [];\n" + - "\t\t\t\tconst committed = sections.find((s) => s && s.name === \"dsh-purge:committed\");\n" + - "\t\t\t\tif (committed && String(committed.text || \"\").trim()) return [{ ...complete, name: complete.name, text: committed.text }];\n" + "\t\t\t\tconst inject = sections.filter((s) => String(s && s.name || \"\").startsWith(\"dsh-purge\")).map((s) => String(s.text || \"\")).filter((t) => t.length > 0).join(\"\\n\\n\");\n" + "\t\t\t\tconst folded = sections.find((s) => s && s.name === complete.name);\n" + "\t\t\t\tconst base = folded && typeof folded.text === \"string\" ? { ...complete, text: folded.text } : { ...complete };\n" + @@ -2988,7 +2986,15 @@ const NEW_TOOL_PATCHES = [ "\t\t\tcontexts: runtimeContextSuppressed ? [] : transformed.contexts\n" + "\t\t};", }, + { + pattern: + "\t\t\t\tconst committed = sections.find((s) => s && s.name === \"dsh-purge:committed\");\n" + + "\t\t\t\tif (committed && String(committed.text || \"\").trim()) return [{ ...complete, name: complete.name, text: committed.text }];\n", + replace: "", + }, ], + // 已打过旧补丁的宿主里还有这行时,不能当成完成,要点一次应用删掉。 + forbid: ["dsh-purge:committed"], markers: ["[dsh-purge] complete prompt keeps inject"], }, { @@ -3533,6 +3539,7 @@ export function sanitizeYamlPersonaScalars(text) { function patchApplied(text, patch) { const hay = asLf(text); + if (Array.isArray(patch.forbid) && patch.forbid.some((marker) => hay.includes(asLf(marker)))) return false; if (Array.isArray(patch.markers) && patch.markers.length > 0) { // markersAny:任一标记即可;默认要全部命中。 const match = patch.markersAny ? "some" : "every"; diff --git a/lib/index.js b/lib/index.js index 48c6d7c..9498b79 100644 --- a/lib/index.js +++ b/lib/index.js @@ -701,12 +701,62 @@ export function apply(ctx, config) { installWebServer(ctx, cfg); } +function headerOf(request, name) { + const headers = request?.headers; + if (!headers) return ""; + const value = headers[name] ?? headers[String(name).toLowerCase()]; + if (Array.isArray(value)) return String(value[0] || ""); + return String(value || ""); +} + +function denyCrossOrigin(response) { + response.writeHead(403, { + "cache-control": "no-store", + "content-type": "application/json; charset=utf-8", + }); + response.end(JSON.stringify({ ok: false, error: "cross-origin blocked" })); +} + +function allowPluginRequest(request, response) { + const site = headerOf(request, "sec-fetch-site").toLowerCase(); + if (site === "cross-site") { + denyCrossOrigin(response); + return false; + } + const origin = headerOf(request, "origin").trim(); + if (origin === "null") { + denyCrossOrigin(response); + return false; + } + if (!origin) return true; + let originHost = ""; + try { + originHost = new URL(origin).host; + } catch { + denyCrossOrigin(response); + return false; + } + const host = headerOf(request, "host").trim(); + if (!host || originHost.toLowerCase() !== host.toLowerCase()) { + denyCrossOrigin(response); + return false; + } + return true; +} + function installWebServer(ctx, cfg) { // 桌面端内嵌 @deepseek-ai/dsh-web-app,设置页同样走 webServer(常见 43120),不是只给官方 dsh web。 watchWebTreeReady(ctx); ctx.inject(["webServer"], (host) => { host.effect(() => { - host.webServer.register({ + const registerPluginRoute = (spec, label) => host.webServer.register({ + ...spec, + handler: async (request, response) => { + if (!allowPluginRequest(request, response)) return; + return spec.handler(request, response); + }, + }, label); + registerPluginRoute({ kind: "exact", path: "/dsh-purge/status", handler: async (request, response) => { @@ -752,7 +802,7 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: status"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/last-user", handler: async (request, response) => { @@ -770,7 +820,7 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: last user"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/rewind/options", handler: async (request, response) => { @@ -788,7 +838,7 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: rewind options"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/rewind", handler: async (request, response) => { @@ -828,7 +878,7 @@ function installWebServer(ctx, cfg) { response.end(); }, }, "dsh-purge: rewind"); - // host.webServer.register({ + // registerPluginRoute({ // kind: "exact", // path: "/dsh-purge/continue", // handler: async (request, response) => { @@ -866,7 +916,7 @@ function installWebServer(ctx, cfg) { // response.end(); // }, // }, "dsh-purge: continue"); - // host.webServer.register({ + // registerPluginRoute({ // kind: "exact", // path: "/dsh-purge/continue/settings", // handler: async (request, response) => { @@ -895,7 +945,7 @@ function installWebServer(ctx, cfg) { // response.end(); // }, // }, "dsh-purge: continue settings"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/update", handler: async (request, response) => { @@ -920,7 +970,7 @@ function installWebServer(ctx, cfg) { response.end(); }, }, "dsh-purge: update"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/apply", handler: async (request, response) => { @@ -984,7 +1034,7 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: apply"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/revert", handler: async (request, response) => { @@ -1008,7 +1058,7 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: revert"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/uninstall", handler: async (request, response) => { @@ -1037,7 +1087,7 @@ function installWebServer(ctx, cfg) { } }, }, "dsh-purge: uninstall"); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/override", handler: async (request, response) => { @@ -1081,7 +1131,7 @@ function installWebServer(ctx, cfg) { }, }, "dsh-purge: override"); installRulesHttp(host.webServer); - host.webServer.register({ + registerPluginRoute({ kind: "exact", path: "/dsh-purge/restart", handler: async (request, response) => { @@ -1211,29 +1261,29 @@ function installRulesHttp(webServer) { }; } -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.writeHead(204, { "cache-control": "no-store" }); response.end(); } function registerRoute(webServer, spec) { try { - return webServer.register(spec); + const handler = spec.handler; + return webServer.register({ + ...spec, + handler: async (request, response) => { + if (!allowPluginRequest(request, response)) return; + return handler(request, response); + }, + }); } catch (e) { console.warn("[dsh-purge] route", spec?.path, String(e && e.message ? e.message : e)); return () => {}; diff --git a/lib/update.js b/lib/update.js index 01876b4..3553591 100644 --- a/lib/update.js +++ b/lib/update.js @@ -469,17 +469,34 @@ function rememberVersion(item, seen) { return item; } -function markCurrent(versions, state, localVer, localSha) { - return (versions || []).map((item) => ({ - ...item, - shaShort: item.shaShort || (item.sha ? String(item.sha).slice(0, 7) : ""), - current: Boolean( - (localSha && item.sha && sameRev(localSha, item.sha)) - || (state.pin && item.ref === state.pin) - || (!state.pin && item.latest && item.channel === state.channel && item.version && item.version === localVer) - || (!state.pin && item.version && item.version === localVer && item.channel === (isBetaName(localVer) ? "beta" : "stable")), - ), - })); +const UPDATE_REF_RE = /^(?:master|beta|v\d+\.\d+[\w.-]{0,48}|[0-9a-f]{7,40})$/i; + +export function safeUpdateRef(ref) { + const target = String(ref || "").trim(); + if (!UPDATE_REF_RE.test(target)) return ""; + return target; +} + +export function markCurrent(versions, state, localVer, localSha) { + const pin = String(state?.pin || ""); + return (versions || []).map((item) => { + const shaHit = Boolean(localSha && item.sha && sameRev(localSha, item.sha)); + const pinHit = Boolean(pin && item.ref === pin); + // 没有本地提交号时,只把本通道「最新」标成当前。同版本号的旧标签不能再标。 + const headHit = Boolean( + !pin + && !localSha + && item.latest + && item.channel === state?.channel + && item.version + && item.version === localVer + ); + return { + ...item, + shaShort: item.shaShort || (item.sha ? String(item.sha).slice(0, 7) : ""), + current: shaHit || pinHit || headHit, + }; + }); } async function listGithubTags() { @@ -589,8 +606,7 @@ function describeLane(id, listed, state, localVer, localRev) { const version = latest?.version || ""; const onLane = state.channel === id; const matchesHead = Boolean(localRev && sha && sameRev(localRev, sha)); - const current = versions.some((item) => item.current) || matchesHead - || Boolean(onLane && version && localVer && version === localVer && !state.pin); + 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)); @@ -708,7 +724,8 @@ function gitResetTo(dir, ref, { force = false } = {}) { if (!force && gitTrackedDirty(dir)) { throw new Error("本地插件文件有未提交改动,未覆盖"); } - const target = String(ref || STABLE_REF); + const target = safeUpdateRef(ref || STABLE_REF); + if (!target) throw new Error("未知版本"); try { runGit(dir, ["fetch", "origin", "--tags"], 60000); } catch { @@ -790,7 +807,8 @@ export async function applyUpdate(jobs = planUpdates(), options = {}) { jobs = planUpdates(); } const state = readChannelState(); - const ref = String(options.ref || currentChannelRef(state) || STABLE_REF); + const ref = safeUpdateRef(options.ref || currentChannelRef(state) || STABLE_REF); + if (!ref) throw new Error("未知版本"); const force = options.force !== false; const zipDirs = []; const vias = new Set(); @@ -884,12 +902,25 @@ export async function switchChannel(channel, { apply = true } = {}) { return applyUpdate(planUpdates(), { ref: CHANNELS[next].ref, channel: next, pin: false, force: true }); } +function listedUpdateRef(target, listed) { + const safe = safeUpdateRef(target); + if (!safe) return ""; + const hit = (listed?.versions || []).find((item) => ( + item.ref === safe + || item.id === safe + || item.sha === safe + || (item.sha && safe.length >= 7 && (item.sha.startsWith(safe) || safe.startsWith(item.sha))) + )); + return safeUpdateRef(hit?.ref || ""); +} + export async function switchVersion(ref) { - const target = String(ref || "").trim(); + const target = safeUpdateRef(ref); if (!target) throw new Error("请选择要回退的版本"); const listed = await listRemoteVersions(); - const hit = listed.versions.find((item) => item.ref === target || item.id === target || item.version === target || item.sha === target); - const resolved = hit?.ref || target; + const resolved = listedUpdateRef(target, listed); + if (!resolved) throw new Error("未知版本"); + const hit = listed.versions.find((item) => item.ref === resolved); const channel = hit?.channel || readChannelState().channel; const pin = hit?.latest ? "" : resolved; return applyUpdate(planUpdates(), { ref: resolved, channel, pin, force: true }); @@ -902,7 +933,13 @@ export async function handleUpdateOp(body = {}) { if (op === "switch" || op === "rollback") return switchVersion(body.ref || body.version || body.id); if (op === "auto") return autoUpdateIfNeeded(); const state = readChannelState(); - const ref = body.ref || currentChannelRef(state); + const requested = body.ref || currentChannelRef(state); + const ref = safeUpdateRef(requested); + if (!ref) throw new Error("未知版本"); + if (ref !== STABLE_REF && ref !== BETA_REF) { + const listed = await listRemoteVersions(); + if (!listedUpdateRef(ref, listed)) throw new Error("未知版本"); + } const channel = body.channel || (ref === BETA_REF ? "beta" : ref === STABLE_REF ? "stable" : state.channel); return applyUpdate(planUpdates(), { ref, channel, pin: false, force: true }); } diff --git a/package.json b/package.json index 0873f3b..9bdac58 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,8 @@ ], "scripts": { "embed-prompt": "node scripts/embed-default-prompt.mjs", - "test:identity": "node scripts/test-identity-assembly.mjs" + "test:identity": "node scripts/test-identity-assembly.mjs", + "test:update": "node scripts/test-update-guards.mjs" }, "license": "MIT", "keywords": [ diff --git a/scripts/test-update-guards.mjs b/scripts/test-update-guards.mjs new file mode 100644 index 0000000..db3a30e --- /dev/null +++ b/scripts/test-update-guards.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { markCurrent, safeUpdateRef } from "../lib/update.js"; + +assert.equal(safeUpdateRef("master"), "master"); +assert.equal(safeUpdateRef("beta"), "beta"); +assert.equal(safeUpdateRef("v1.1.11"), "v1.1.11"); +assert.equal(safeUpdateRef("v1.1.12-beta.1"), "v1.1.12-beta.1"); +assert.equal(safeUpdateRef("9397203733562d6baeec9e38ac519698c619edcb"), "9397203733562d6baeec9e38ac519698c619edcb"); +assert.equal(safeUpdateRef("--hard"), ""); +assert.equal(safeUpdateRef("origin/master"), ""); +assert.equal(safeUpdateRef("../evil"), ""); +assert.equal(safeUpdateRef("master;rm"), ""); + +const head = "9397203733562d6baeec9e38ac519698c619edcb"; +const tag = "5e6be24acc3e5aac981c701cc34ef710ce48c4c7"; +const versions = [ + { id: "master", ref: "master", sha: head, version: "1.1.11", channel: "stable", latest: true }, + { id: "v1.1.11", ref: "v1.1.11", sha: tag, version: "1.1.11", channel: "stable" }, +]; +const marked = markCurrent(versions, { channel: "stable", pin: "" }, "1.1.11", head); +assert.equal(marked.find((item) => item.ref === "master").current, true); +assert.equal(marked.find((item) => item.ref === "v1.1.11").current, false); + +const onTag = markCurrent(versions, { channel: "stable", pin: "v1.1.11" }, "1.1.11", tag); +assert.equal(onTag.find((item) => item.ref === "v1.1.11").current, true); +assert.equal(onTag.find((item) => item.ref === "master").current, false); + +console.log("ok: update guards");