From cd8687043f426cf78140c85784f04282bbe2e0bc Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 15:21:36 -0300 Subject: [PATCH 1/3] Detect the official DeepSeek Harness dsh.cmd launcher on Windows The CLI installer writes dsh.cmd, but discovery only looked for dsh.exe. Normalize the official batch shim into the executable, argument prefix and environment the launcher declares, keeping the argument-array spawn sites unchanged. The parser accepts only the official layout, binds the Electron entry to the owning installation, checks both files on disk, and leaves other shims to the node_modules fallback. --- runtime/commands.ts | 79 ++++++++- tests/windows-command-discovery.test.ts | 224 ++++++++++++++++++++++++ 2 files changed, 296 insertions(+), 7 deletions(-) create mode 100644 tests/windows-command-discovery.test.ts diff --git a/runtime/commands.ts b/runtime/commands.ts index 112f0d5..54e1cba 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -1,6 +1,14 @@ -import { access, readdir, stat } from "node:fs/promises"; +import { access, readdir, readFile, stat } from "node:fs/promises"; import { constants } from "node:fs"; -import { delimiter, dirname, isAbsolute, join } from "node:path"; +import { + basename, + delimiter, + dirname, + isAbsolute, + join, + resolve, + sep, +} from "node:path"; import { homedir } from "node:os"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; @@ -95,6 +103,51 @@ async function direct( return null; } +const WINDOWS_DSH_SHIM = + /^\s*"%~dp0\\?([^"%\r\n]+\.exe)"\s+--expose-internals\s+"%~dp0\\?([^"%\r\n]+\.(?:c|m)?js)"\s+%\*\s*$/i; + +/** + * The launcher installed by the official DeepSeek Harness CLI is a .cmd shim + * that delegates to an Electron executable. Worker sessions spawn with + * `shell: false`, which cannot run a batch file on Windows. Normalize the shim + * into the executable, argument prefix and environment the installer declares, + * so every existing argument-array spawn site works unchanged. + */ +async function windowsShimCommand(path: string): Promise { + let text: string; + try { + text = await readFile(path, "utf8"); + } catch { + return null; + } + // Only a line that fully matches the official launcher shape counts. A + // comment or echo that merely mentions the flag cannot shadow the real line. + let match: RegExpMatchArray | null = null; + for (const line of text.split(/\r?\n/)) { + match = line.match(WINDOWS_DSH_SHIM); + if (match) break; + } + if (!match) return null; + const base = dirname(path); + const command = resolve(base, match[1]); + const script = resolve(base, match[2]); + // Bind the entry to the installation that owns the executable, so a changed + // .exe cannot keep a saved worker approval for the same script identity. + if (basename(command).toLowerCase() !== "deepseek harness.exe") return null; + const appAsar = join(dirname(command), "resources", "app.asar"); + if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) + return null; + // A leftover shim from an uninstall must not look "installed", and must not + // block the node_modules fallback in the same directory. + if (!(await exists(command)) || !(await exists(appAsar))) return null; + return { + command, + prefix: ["--expose-internals", script], + identity: script, + env: { ELECTRON_RUN_AS_NODE: "1" }, + }; +} + async function cursorRuntime(): Promise { const root = join(homedir(), "AppData", "Local", "cursor-agent", "versions"); try { @@ -227,19 +280,31 @@ export async function findCommand( .filter(Boolean), ), ]; + const extensions = + process.platform === "win32" + ? name === "dsh" + ? [".exe", ".cmd"] + : [".exe"] + : [""]; for (const dir of dirs) { const names = name === "cursor" ? ["cursor-agent", "agent"] : [name]; for (const candidate of names) { - const path = join( - dir, - candidate + (process.platform === "win32" ? ".exe" : ""), - ); - if ((await exists(path)) && (await stat(path)).isFile()) + for (const extension of extensions) { + const path = join(dir, candidate + extension); + if (!((await exists(path)) && (await stat(path)).isFile())) continue; + // A batch shim cannot be passed to spawn with `shell: false`. + if (extension !== ".exe") { + const normalized = + name === "dsh" ? await windowsShimCommand(path) : null; + if (normalized) return normalized; + continue; + } return { command: path, prefix: [], ...(name === "cursor" ? { env: { CURSOR_INVOKED_AS: "agent" } } : {}), }; + } } const packageEntry = name === "memtrace" diff --git a/tests/windows-command-discovery.test.ts b/tests/windows-command-discovery.test.ts new file mode 100644 index 0000000..cffceee --- /dev/null +++ b/tests/windows-command-discovery.test.ts @@ -0,0 +1,224 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { commandIdentity, findCommand } from "../runtime/commands"; + +// Byte-for-byte shape of the launcher written by the official DSH installer, +// including CRLF and the real relative depths from resources/runtime/cli/bin. +const officialShim = [ + "@echo off", + "setlocal DisableDelayedExpansion", + 'set "ELECTRON_RUN_AS_NODE=1"', + '"%~dp0..\\..\\..\\..\\DeepSeek Harness.exe" --expose-internals "%~dp0..\\..\\..\\app.asar\\dsh\\node_modules\\@deepseek-ai\\dsh-desktop-host\\lib\\cli.js" %*', + "exit /b %errorlevel%", + "", +].join("\r\n"); + +async function fixture(t: test.TestContext) { + const root = await mkdtemp(join(tmpdir(), "memcode-win-discovery-")); + t.after(() => rm(root, { recursive: true, force: true })); + const install = join(root, "install"); + const bin = join(install, "resources", "runtime", "cli", "bin"); + await mkdir(bin, { recursive: true }); + const exe = join(install, "DeepSeek Harness.exe"); + const asar = join(install, "resources", "app.asar"); + await writeFile(exe, "fixture-only"); + await writeFile(asar, "fixture-only"); + const script = join( + install, + "resources", + "app.asar", + "dsh", + "node_modules", + "@deepseek-ai", + "dsh-desktop-host", + "lib", + "cli.js", + ); + const before = process.env.PATH; + process.env.PATH = bin; + t.after(() => { + if (before === undefined) delete process.env.PATH; + else process.env.PATH = before; + }); + return { root, install, bin, exe, asar, script }; +} + +test( + "the real dsh.cmd layout is normalized for argument-array spawn", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + + const command = await findCommand("dsh"); + assert.ok(command, "the .cmd launcher must be discovered"); + assert.equal(command.command, f.exe); + assert.deepEqual(command.prefix, ["--expose-internals", f.script]); + assert.equal(command.env?.ELECTRON_RUN_AS_NODE, "1"); + assert.equal(commandIdentity(command), f.script); + }, +); + +test( + "a real dsh.exe in the same directory still wins over the dsh.cmd launcher", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + const exe = join(f.bin, "dsh.exe"); + await writeFile(exe, "fixture-only"); + + const command = await findCommand("dsh"); + assert.equal(command?.command, exe); + assert.deepEqual(command?.prefix, []); + }, +); + +test( + "an unrelated .cmd is never handed to a shell:false spawn", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), "@echo off\r\nfixture-only\r\n"); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "a rem line containing --expose-internals cannot spoof the launcher", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + `@echo off\r\nrem "C:\\evil.exe" --expose-internals "a.js"\r\n${officialShim}`, + ); + + const command = await findCommand("dsh"); + assert.equal(command?.command, f.exe); + assert.deepEqual(command?.prefix, ["--expose-internals", f.script]); + }, +); + +test( + "an executable with a different name cannot borrow the DSH launcher identity", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.install, "Other.exe"), "fixture-only"); + await writeFile( + join(f.bin, "dsh.cmd"), + officialShim.replace("DeepSeek Harness.exe", "Other.exe"), + ); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "an entry outside the installation's app.asar is rejected", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + officialShim.replace( + "app.asar\\dsh\\node_modules\\@deepseek-ai\\dsh-desktop-host\\lib\\cli.js", + "other\\cli.js", + ), + ); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "a shim from an incomplete installation without app.asar is ignored", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + await rm(f.asar); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "an echo mentioning the flag cannot shadow the real launcher line", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + `@echo off\r\necho "%~dp0..\\..\\..\\..\\Other.exe" --expose-internals "x.js" %*\r\n${officialShim}`, + ); + + const command = await findCommand("dsh"); + assert.equal(command?.command, f.exe); + assert.deepEqual(command?.prefix, ["--expose-internals", f.script]); + }, +); + +test( + "a leftover shim whose executable is gone is ignored", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + await rm(f.exe); + + assert.equal(await findCommand("dsh"), null); + }, +); + +test( + "an npm-style cmd shim cannot displace the node_modules fallback", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile( + join(f.bin, "dsh.cmd"), + '"%~dp0\\node.exe" --expose-internals "%~dp0\\node_modules\\@deepseek-ai\\dsh\\lib\\bin.js" %*\r\n', + ); + const fallback = join( + f.bin, + "node_modules", + "@deepseek-ai", + "dsh", + "lib", + "bin.js", + ); + await mkdir(join(f.bin, "node_modules", "@deepseek-ai", "dsh", "lib"), { + recursive: true, + }); + await writeFile(fallback, ""); + + const command = await findCommand("dsh"); + assert.equal(command?.command, process.execPath); + assert.deepEqual(command?.prefix, [fallback]); + }, +); + +test( + "between PATH directories the first entry wins, even when it only has a .cmd", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await fixture(t); + await writeFile(join(f.bin, "dsh.cmd"), officialShim); + const other = join(f.root, "other"); + await mkdir(other, { recursive: true }); + const otherExe = join(other, "dsh.exe"); + await writeFile(otherExe, "fixture-only"); + + process.env.PATH = `${f.bin};${other}`; + assert.equal((await findCommand("dsh"))?.command, f.exe); + + process.env.PATH = `${other};${f.bin}`; + assert.equal((await findCommand("dsh"))?.command, otherExe); + }, +); From 98fa75401a69795b28c77c5432f3d5ab848d827e Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 16:38:55 -0300 Subject: [PATCH 2/3] fix: keep extensionless PATH commands discoverable outside Windows Shim normalization ran for every extension other than .exe. On Linux the extension list is [""], so each PATH executable entered that branch and was skipped unless a node_modules fallback existed; git, gh and shell lookups could return null. Normalize only .cmd files so native executables reach the direct return. --- runtime/commands.ts | 2 +- tests/linux-command-discovery.test.ts | 39 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/linux-command-discovery.test.ts diff --git a/runtime/commands.ts b/runtime/commands.ts index 54e1cba..c01d4e9 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -293,7 +293,7 @@ export async function findCommand( const path = join(dir, candidate + extension); if (!((await exists(path)) && (await stat(path)).isFile())) continue; // A batch shim cannot be passed to spawn with `shell: false`. - if (extension !== ".exe") { + if (extension === ".cmd") { const normalized = name === "dsh" ? await windowsShimCommand(path) : null; if (normalized) return normalized; diff --git a/tests/linux-command-discovery.test.ts b/tests/linux-command-discovery.test.ts new file mode 100644 index 0000000..0d6e899 --- /dev/null +++ b/tests/linux-command-discovery.test.ts @@ -0,0 +1,39 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { findCommand } from "../runtime/commands"; + +async function linuxPathFixture(t: test.TestContext, names: string[]) { + const root = await mkdtemp(join(tmpdir(), "memcode-linux-discovery-")); + t.after(() => rm(root, { recursive: true, force: true })); + const commands = new Map(); + for (const name of names) { + const path = join(root, name); + await writeFile(path, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + commands.set(name, path); + } + const beforePath = process.env.PATH; + const beforePlatform = Object.getOwnPropertyDescriptor(process, "platform"); + process.env.PATH = root; + // findCommand reads process.platform directly. Stub it so this regression is + // observable on a Windows development machine as well as on Linux CI. + Object.defineProperty(process, "platform", { + value: "linux", + configurable: true, + }); + t.after(() => { + if (beforePlatform) + Object.defineProperty(process, "platform", beforePlatform); + if (beforePath === undefined) delete process.env.PATH; + else process.env.PATH = beforePath; + }); + return commands; +} + +test("extensionless PATH executables are discovered on Linux", async (t) => { + const commands = await linuxPathFixture(t, ["git", "gh", "dsh"]); + for (const [name, path] of commands) + assert.deepEqual(await findCommand(name), { command: path, prefix: [] }); +}); From 3b782074a55c8188f0d316f9829e171eb8f9e2fd Mon Sep 17 00:00:00 2001 From: magalz Date: Sat, 21 Nov 2026 17:47:21 -0300 Subject: [PATCH 3/3] fix: rediscover saved dsh identities inside app.asar A GUI launch without the installer's launcher directory on PATH could not reuse an approved dsh runtime: its saved identity points inside app.asar, which ordinary filesystem access cannot read. Reconstruct the Electron command from the owning executable and archive before the configured-path existence check, sharing the validation used for the .cmd shim. Reject non-canonical paths so an identity cannot traverse into another installation. --- runtime/commands.ts | 71 ++++++++++++++++----- tests/windows-command-discovery.test.ts | 83 ++++++++++++++++++++++++- 2 files changed, 138 insertions(+), 16 deletions(-) diff --git a/runtime/commands.ts b/runtime/commands.ts index c01d4e9..7243235 100644 --- a/runtime/commands.ts +++ b/runtime/commands.ts @@ -6,6 +6,7 @@ import { dirname, isAbsolute, join, + normalize, resolve, sep, } from "node:path"; @@ -106,6 +107,58 @@ async function direct( const WINDOWS_DSH_SHIM = /^\s*"%~dp0\\?([^"%\r\n]+\.exe)"\s+--expose-internals\s+"%~dp0\\?([^"%\r\n]+\.(?:c|m)?js)"\s+%\*\s*$/i; +async function dshInstallCommand( + executable: string, + script: string, +): Promise { + // Bind the entry to the installation that owns the executable, so a changed + // .exe cannot keep a saved worker approval for the same script identity. + if (basename(executable).toLowerCase() !== "deepseek harness.exe") + return null; + const appAsar = join(dirname(executable), "resources", "app.asar"); + if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) + return null; + // A leftover shim from an uninstall must not look "installed", and must not + // block the node_modules fallback in the same directory. + if (!(await exists(executable)) || !(await exists(appAsar))) return null; + return { + command: executable, + prefix: ["--expose-internals", script], + identity: script, + env: { ELECTRON_RUN_AS_NODE: "1" }, + }; +} + +/** + * A saved dsh identity points inside the installer's app.asar, which ordinary + * filesystem access cannot read. Rebuild the command from the owning + * installation before the configured-path existence check rejects it. + */ +async function savedArchiveCommand( + name: string, + configured: string, +): Promise { + if (name !== "dsh" || process.platform !== "win32" || !isAbsolute(configured)) + return null; + const normalized = normalize(configured); + // A saved identity must be the exact entry the shim resolved. Reject `..` + // segments that would redirect an approved identity to another installation. + if (normalized.toLowerCase() !== configured.toLowerCase()) return null; + const parts = normalized.split(sep); + const archive = parts.findLastIndex( + (part) => part.toLowerCase() === "app.asar", + ); + if ( + archive < 2 || + parts[archive - 1]?.toLowerCase() !== "resources" || + archive === parts.length - 1 || + !/\.(?:c|m)?js$/i.test(parts[parts.length - 1]) + ) + return null; + const install = parts.slice(0, archive - 1).join(sep); + return dshInstallCommand(join(install, "DeepSeek Harness.exe"), normalized); +} + /** * The launcher installed by the official DeepSeek Harness CLI is a .cmd shim * that delegates to an Electron executable. Worker sessions spawn with @@ -131,21 +184,7 @@ async function windowsShimCommand(path: string): Promise { const base = dirname(path); const command = resolve(base, match[1]); const script = resolve(base, match[2]); - // Bind the entry to the installation that owns the executable, so a changed - // .exe cannot keep a saved worker approval for the same script identity. - if (basename(command).toLowerCase() !== "deepseek harness.exe") return null; - const appAsar = join(dirname(command), "resources", "app.asar"); - if (!script.toLowerCase().startsWith((appAsar + sep).toLowerCase())) - return null; - // A leftover shim from an uninstall must not look "installed", and must not - // block the node_modules fallback in the same directory. - if (!(await exists(command)) || !(await exists(appAsar))) return null; - return { - command, - prefix: ["--expose-internals", script], - identity: script, - env: { ELECTRON_RUN_AS_NODE: "1" }, - }; + return dshInstallCommand(command, script); } async function cursorRuntime(): Promise { @@ -250,6 +289,8 @@ export async function findCommand( options: MacCommandOptions & { platform?: NodeJS.Platform } = {}, ): Promise { if (configured) { + const archived = await savedArchiveCommand(name, configured); + if (archived) return archived; if (!isAbsolute(configured) || !(await exists(configured))) return null; if (/\.(cjs|mjs|js)$/i.test(configured)) return { diff --git a/tests/windows-command-discovery.test.ts b/tests/windows-command-discovery.test.ts index cffceee..64cd71e 100644 --- a/tests/windows-command-discovery.test.ts +++ b/tests/windows-command-discovery.test.ts @@ -2,7 +2,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join, normalize, relative, sep } from "node:path"; import { commandIdentity, findCommand } from "../runtime/commands"; // Byte-for-byte shape of the launcher written by the official DSH installer, @@ -222,3 +222,84 @@ test( assert.equal((await findCommand("dsh"))?.command, otherExe); }, ); + +async function withoutLauncherInPath(t: test.TestContext) { + const f = await fixture(t); + const elsewhere = join(f.root, "empty-path"); + await mkdir(elsewhere, { recursive: true }); + process.env.PATH = elsewhere; + return f; +} + +test( + "a saved app.asar identity rediscovers the harness without the launcher directory in PATH", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + assert.equal( + await findCommand("dsh"), + null, + "the installer's launcher directory must be absent", + ); + + const command = await findCommand("dsh", f.script); + assert.ok(command, "the saved identity must rediscover the installation"); + assert.equal(command.command, f.exe); + assert.deepEqual(command.prefix, ["--expose-internals", f.script]); + assert.equal(commandIdentity(command), f.script); + assert.equal(command.env?.ELECTRON_RUN_AS_NODE, "1"); + }, +); + +test( + "a saved archive identity is only reconstructed from a still matching installation", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + assert.equal( + await findCommand("codex", f.script), + null, + "another harness must not inherit the dsh archive identity", + ); + + await rm(f.exe); + assert.equal(await findCommand("dsh", f.script), null); + await writeFile(f.exe, "fixture-only"); + + await rm(f.asar); + assert.equal(await findCommand("dsh", f.script), null); + }, +); + +test( + "a configured executable path keeps its direct-command behavior", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + assert.equal((await findCommand("dsh", f.exe))?.command, f.exe); + }, +); + +test( + "a saved archive identity cannot traverse into another installation", + { skip: process.platform !== "win32" }, + async (t) => { + const f = await withoutLauncherInPath(t); + const other = join(f.root, "other"); + const otherScript = join( + other, + "resources", + "app.asar", + "dsh", + "cli.js", + ); + await mkdir(join(other, "resources"), { recursive: true }); + await writeFile(join(other, "DeepSeek Harness.exe"), "fixture-only"); + await writeFile(join(other, "resources", "app.asar"), "fixture-only"); + + const from = dirname(f.script); + const forged = from + sep + relative(from, otherScript); + assert.equal(normalize(forged), otherScript); + assert.equal(await findCommand("dsh", forged), null); + }, +);