@linxin666/dsh-win-bash 0.4.14 → 0.4.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # node scripts/verify-docs.mjs --write <dir>
5
- README.md: c0a834ef30c039c5dc5b625b4d0fbacefc6bb35e
6
- README.zh.md: 1b50b301e2fad0f541d5058b1ef3e0b733d96f8b
5
+ README.md: 0ecbceaea0a26781ee3b0340d8c55ee0aec4b61e
6
+ README.zh.md: b0124801c815f6ca3520bba370cf8a63e0621801
package/README.md CHANGED
@@ -47,6 +47,7 @@ session is what makes that true.
47
47
  job settles. Directories a killed host never got to delete are reclaimed on the
48
48
  next start, by the pid in their name, so the temp root does not grow one
49
49
  directory per shell.
50
+ - Supplies every shell with an explicit `HOME`: an existing host value is preserved, otherwise Node's Unicode user-home path is used so a non-ASCII Windows profile does not pass through MSYS's ANSI inference.
50
51
  - Verifies the vendored payload against its SHA256 manifest and publishes a
51
52
  verified copy under the DSH home before the tool is registered at all; a
52
53
  mismatch refuses the mount, and every shell runs from that copy rather than
@@ -257,6 +258,24 @@ anything runs, and an isolated `DSH_HOME` gets its own cache. When that copy
257
258
  cannot be written, the verified packaged tree runs instead and one warning line
258
259
  says so.
259
260
 
261
+ Matching the manifest is not enough to make a copy safe to run. A Windows
262
+ mandatory integrity label lives in the file's security descriptor, not in its
263
+ bytes: a data tree carrying an inheritable Low label gives the copied
264
+ `bash.exe` a Low label, and Windows then starts a Low-integrity process even
265
+ from a Medium runner. That process cannot write an ordinary Medium workspace or
266
+ temp directory. Before a copy is reused, before one is published, and again
267
+ after publication, `win_bash` reads the mandatory labels of the directory chain
268
+ and of `bash.exe` through the Windows `icacls` SDDL output. A Low or Untrusted
269
+ tree is never reused and never spawned from; the payload is published into an
270
+ isolated per-user cache root instead (still outside the package), so a stale Low
271
+ cache is abandoned rather than kept alive across restarts and updates. This
272
+ checks metadata only: it never changes a label, a DACL or a token, and it never
273
+ asks the user to lower a workspace label, change the sandbox policy or run DSH
274
+ elevated. If no safe cache root exists, the verified packaged tree runs with an
275
+ explicit warning; only when even that image is labelled Low does the mount fail
276
+ with `unsafe-integrity` and name the `pwsh` fallback. Set
277
+ `DSH_WIN_BASH_RUNTIME_HOME` to override the isolated cache root's parent.
278
+
260
279
  ## Known limitations
261
280
 
262
281
  - Windows x64 only. The payload is a Windows MSYS2 build and the tool refuses
@@ -271,8 +290,9 @@ says so.
271
290
  - A background job is one command in one process: it has no persistent state
272
291
  across jobs, and it cannot be promoted from a running foreground call
273
292
  (a foreground call that hits `timeoutMs` still stops its shell).
274
- - The published payload lives under `<DSH_HOME>/win-bash/runtime/`. Each
275
- distinct payload keeps one directory there, about 16 MiB, and such a
293
+ - The published payload normally lives under `<DSH_HOME>/win-bash/runtime/`,
294
+ and in the isolated per-user cache root when that data tree is labelled Low.
295
+ Each distinct payload keeps one directory there, about 16 MiB, and such a
276
296
  directory can be deleted while DSH is stopped: the next mount publishes it
277
297
  again.
278
298
 
package/README.zh.md CHANGED
@@ -35,6 +35,7 @@ shell 必须持久,因为 shell 是有状态的:一条命令 `cd` 过、expo
35
35
  shell 结束时删除它——正常 `exit`、超时或中止、会话销毁、插件卸载,以及后台任务
36
36
  结算时都在内。宿主被强杀、来不及删除的目录,会在下次启动时按目录名里的 pid 回收,
37
37
  因此 temp 根不会每个 shell 攒一个目录。
38
+ - 为每个 shell 显式提供 `HOME`:保留宿主已有值,缺失时使用 Node 返回的 Unicode 用户目录,避免非 ASCII Windows 用户目录经过 MSYS 的 ANSI 推导而损坏。
38
39
  - 工具注册之前先按 SHA256 清单校验随包载荷,并把校验过的副本发布到 DSH home
39
40
  下;摘要不匹配即拒绝挂载,且每个 shell 都从该副本启动,而不是从包目录启动。
40
41
  - `win_bash` 注册期间,把宿主自带的 `pwsh` 工具从会话的模型可见面上替换掉,
@@ -210,6 +211,18 @@ shell、其 userland 以及精确的 DLL 闭包。同一 release 的两份资产
210
211
  的发布会复用已有副本,字节与清单不符的副本会在运行之前被重建,独立的 `DSH_HOME`
211
212
  得到自己的缓存。副本写不出来时,改由校验过的包内树运行,并有一条警告说明这一点。
212
213
 
214
+ 清单匹配还不足以让副本「可以运行」。Windows 强制性完整性标签在文件的安全描述符里,
215
+ 不在字节里:数据树带可继承的 Low 标签时,复制出的 `bash.exe` 也带 Low 标签,于是
216
+ Windows 即使从 Medium runner 启动也会得到 Low 完整性进程,写不了普通 Medium 工作区与
217
+ 临时目录。因此 `win_bash` 在复用副本前、发布副本前、以及发布之后,都会通过 Windows
218
+ `icacls` 的 SDDL 输出核验目录链与 `bash.exe` 的强制性完整性标签。带 Low/Untrusted
219
+ 标签的树不复用、不执行;载荷改为发布到隔离的每用户缓存根(仍在包外),旧 Low 缓存
220
+ 因此被弃用,不会在重启或更新后靠哈希匹配继续存活。这里只读取元数据:不改任何标签、
221
+ DACL 或令牌,也不要求用户降低工作区标签、修改沙箱策略或提权运行 DSH。没有安全候选
222
+ 根时,改由校验过的包内树运行并给出明确警告;只有连包内映像都带 Low 标签,才以
223
+ `unsafe-integrity` 拒绝挂载并指明 `pwsh` 退路。可用 `DSH_WIN_BASH_RUNTIME_HOME`
224
+ 覆盖隔离缓存根的父目录。
225
+
213
226
  ## 已知限制
214
227
 
215
228
  - 仅支持 Windows x64。载荷是 Windows MSYS2 构建,工具在任何其它平台或架构上都拒绝
@@ -222,8 +235,9 @@ shell、其 userland 以及精确的 DLL 闭包。同一 release 的两份资产
222
235
  字节,以及在 provider 留下 spill 文件时完整流在哪里。
223
236
  - 后台任务是「一个进程执行一条命令」:任务之间没有持久状态,也不能由正在跑的前台调用
224
237
  「升级」而来(前台调用到达 `timeoutMs` 时仍然会停掉它的 shell)。
225
- - 发布的载荷位于 `<DSH_HOME>/win-bash/runtime/`。每一份不同的载荷在那里保留一个
226
- 目录(约 16 MiB),DSH 停止时可以安全删除它:下一次挂载会重新发布。
238
+ - 发布的载荷通常位于 `<DSH_HOME>/win-bash/runtime/`;当该数据树带 Low 标签时,
239
+ 改放在隔离的每用户缓存根。每一份不同的载荷在那里保留一个目录(约 16 MiB),DSH
240
+ 停止时可以安全删除它:下一次挂载会重新发布。
227
241
 
228
242
  ## 后续工作
229
243
 
package/lib/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
2
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync } from "node:fs";
3
3
  import { rm } from "node:fs/promises";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { dirname, isAbsolute, join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
8
+ import { spawnSync } from "node:child_process";
8
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
- //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.8.6/node_modules/@deepseek-ai/cosmokit/lib/index.js
10
+ //#region ../../node_modules/.pnpm/@deepseek-ai+cosmokit@1.9.0/node_modules/@deepseek-ai/cosmokit/lib/index.js
10
11
  /** Return true when a value is `null` or `undefined`. */
11
12
  function isNullable(value) {
12
13
  return value === null || value === void 0;
@@ -260,7 +261,7 @@ var Time;
260
261
  Time.template = template;
261
262
  })(Time || (Time = {}));
262
263
  //#endregion
263
- //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.18.5/node_modules/@deepseek-ai/schemastery/lib/index.mjs
264
+ //#region ../../node_modules/.pnpm/@deepseek-ai+schemastery@3.19.0/node_modules/@deepseek-ai/schemastery/lib/index.mjs
264
265
  const kSchema = Symbol.for("schemastery");
265
266
  const kValidationError = Symbol.for("ValidationError");
266
267
  globalThis.__schemastery_index__ ??= 0;
@@ -1055,11 +1056,12 @@ function shellArgv(runtime) {
1055
1056
  * The environment contract every pinned shell starts with.
1056
1057
  * @param runtime - the verified payload paths.
1057
1058
  * @param temp - the private temp directory that shell owns.
1058
- * @param base - the ambient environment the PATH is appended to.
1059
+ * @param base - the ambient environment whose PATH and HOME are inherited.
1059
1060
  * @returns the entries this tool sets explicitly.
1060
1061
  */
1061
1062
  function shellEnvironment(runtime, temp, base = process.env) {
1062
1063
  return {
1064
+ HOME: base.HOME ?? homedir(),
1063
1065
  PATH: runtime.bin + (process.platform === "win32" ? ";" : ":") + (base.PATH ?? ""),
1064
1066
  TMPDIR: temp,
1065
1067
  TMP: temp,
@@ -2183,6 +2185,97 @@ function resolveDshHome(env = process.env, home = homedir()) {
2183
2185
  }
2184
2186
  return j(home, ".dsh");
2185
2187
  }
2188
+ /** Wall-clock bound on one icacls query for a security descriptor. */
2189
+ const READ_LABEL_TIMEOUT_MS = 5e3;
2190
+ /** One mandatory-label ACE inside an SDDL SACL: (ML;flags;rights;;;SID). */
2191
+ const MANDATORY_LABEL_ACE = /\(ML;[^)]*;([^;)]+)\)/gi;
2192
+ /**
2193
+ * Classify the mandatory label ACEs of one icacls /save SDDL blob.
2194
+ *
2195
+ * A missing SACL means the object has no explicit label and inherits Medium by
2196
+ * default. High/System/Medium labels are harmless here; only Low or Untrusted
2197
+ * can turn a Medium runner's child into a Low process.
2198
+ * @param sddl - the UTF-16LE-decoded contents of an icacls /save file.
2199
+ * @returns the label verdict. `unknown` is reserved for the reader that could
2200
+ * not obtain or trust a descriptor at all; a parsed blob always decides.
2201
+ */
2202
+ function parseIntegritySddl(sddl) {
2203
+ const sacl = /S:([^\r\n]*)/.exec(sddl)?.[1] ?? "";
2204
+ for (const match of sacl.matchAll(MANDATORY_LABEL_ACE)) {
2205
+ const sid = (match[1] ?? "").trim().toUpperCase();
2206
+ if (sid === "LW") return "low-or-untrusted";
2207
+ const numeric = /^S-1-16-(\d+)$/.exec(sid);
2208
+ if (numeric !== null && Number(numeric[1]) < 8192) return "low-or-untrusted";
2209
+ }
2210
+ return "medium-or-higher";
2211
+ }
2212
+ /** Absolute path of the Windows icacls binary, never resolved through PATH. */
2213
+ function icaclsPath(env) {
2214
+ return join(env.SystemRoot ?? env.windir ?? "C:\\Windows", "System32", "icacls.exe");
2215
+ }
2216
+ /**
2217
+ * Read one existing path's mandatory integrity label.
2218
+ *
2219
+ * On a POSIX host there is no Windows mandatory integrity control (and this
2220
+ * package does not mount there), so the label cannot downgrade anything. A
2221
+ * missing icacls, a failed query or an unreadable descriptor is reported as
2222
+ * `unknown` rather than guessed: the caller decides whether to fall back.
2223
+ * @param target - an existing file or directory to inspect.
2224
+ * @param env - environment supplying SystemRoot; the live one by default.
2225
+ * @returns the label verdict.
2226
+ */
2227
+ function readMandatoryLabel(target, env = process.env) {
2228
+ if (process.platform !== "win32") return "medium-or-higher";
2229
+ const exe = icaclsPath(env);
2230
+ if (!existsSync(exe)) return "unknown";
2231
+ let scratch;
2232
+ let aclFile;
2233
+ try {
2234
+ scratch = mkdtempSync(join(tmpdir(), "dsh-win-bash-acl-"));
2235
+ aclFile = join(scratch, "acl-" + randomUUID().slice(0, 8) + ".txt");
2236
+ const run = spawnSync(exe, [
2237
+ target,
2238
+ "/save",
2239
+ aclFile
2240
+ ], {
2241
+ windowsHide: true,
2242
+ timeout: READ_LABEL_TIMEOUT_MS,
2243
+ stdio: "ignore"
2244
+ });
2245
+ if (run.error !== void 0 || run.status !== 0 || !existsSync(aclFile)) return "unknown";
2246
+ return parseIntegritySddl(readFileSync(aclFile).toString("utf16le"));
2247
+ } catch {
2248
+ return "unknown";
2249
+ } finally {
2250
+ if (aclFile !== void 0) try {
2251
+ unlinkSync(aclFile);
2252
+ } catch {}
2253
+ if (scratch !== void 0) try {
2254
+ rmdirSync(scratch);
2255
+ } catch {}
2256
+ }
2257
+ }
2258
+ /**
2259
+ * Every existing path from `path` up to the volume root.
2260
+ *
2261
+ * A cache root can sit several levels below the data tree that a workspace
2262
+ * sandbox labelled Low, and an inheritable ACE on ANY of those ancestors can
2263
+ * still be propagated onto existing children later. Checking only the nearest
2264
+ * existing ancestor would miss that, so the whole chain is inspected.
2265
+ * @param path - the prospective path (it need not exist yet).
2266
+ * @returns the existing ancestors, nearest first.
2267
+ */
2268
+ function existingAncestors(path) {
2269
+ const found = [];
2270
+ let current = resolve(path);
2271
+ for (let depth = 0; depth < 32; depth += 1) {
2272
+ if (existsSync(current)) found.push(current);
2273
+ const parent = dirname(current);
2274
+ if (parent === current) break;
2275
+ current = parent;
2276
+ }
2277
+ return found;
2278
+ }
2186
2279
  //#endregion
2187
2280
  //#region src/runtime.ts
2188
2281
  /**
@@ -2192,7 +2285,7 @@ function resolveDshHome(env = process.env, home = homedir()) {
2192
2285
  * The package ships its own Git for Windows MinGit extraction under
2193
2286
  * runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
2194
2287
  * (a host Git for Windows install, WSL, or a stray MSYS), because the whole
2195
- * point of vendoring is a shell whose version and bytes are pinned. Three
2288
+ * point of vendoring is a shell whose version and bytes are pinned. Four
2196
2289
  * invariants implement that:
2197
2290
  *
2198
2291
  * 1. the binary is addressed by absolute path, never by name,
@@ -2200,6 +2293,13 @@ function resolveDshHome(env = process.env, home = homedir()) {
2200
2293
  * packaging time before it is used at all, and
2201
2294
  * 3. the tree that RUNS is a published copy under the DSH home, not the tree
2202
2295
  * inside the package.
2296
+ * 4. the copy's Windows mandatory integrity label is checked before it is
2297
+ * reused or before a freshly published copy is spawned. A Low (or lower)
2298
+ * label on the executable image makes Windows start a Low-integrity process
2299
+ * even from a Medium runner, and that process cannot write an ordinary
2300
+ * Medium workspace or temp directory. Such a tree is never used: the payload
2301
+ * is published into an isolated cache root instead, and if no candidate root
2302
+ * is safe the mount is refused with a specific diagnosis.
2203
2303
  *
2204
2304
  * The third invariant is why this module publishes a cache: Windows refuses to
2205
2305
  * rename a directory whose executable is running, and pnpm imports a package by
@@ -2233,6 +2333,18 @@ const CHECKSUM_FILE = "checksums.sha256";
2233
2333
  */
2234
2334
  const CACHE_DIR_PARTS = ["win-bash", "runtime"];
2235
2335
  /**
2336
+ * Directory parts of the isolated fallback cache, used only when the preferred
2337
+ * cache root carries a Low mandatory integrity label. It lives outside the DSH
2338
+ * data tree, which a workspace sandbox can label Low with an inheritable ACE.
2339
+ */
2340
+ const ISOLATED_CACHE_DIR_PARTS = ["dsh-win-bash", "runtime"];
2341
+ /**
2342
+ * Optional environment override for the isolated cache root's parent. An
2343
+ * operator whose local app data is itself labelled Low can point this at a
2344
+ * directory they have verified is Medium; it is not needed on a normal host.
2345
+ */
2346
+ const RUNTIME_ROOT_ENV = "DSH_WIN_BASH_RUNTIME_HOME";
2347
+ /**
2236
2348
  * Name prefix of the staging directory one cache copy is built in. The rest of
2237
2349
  * the name is the payload key, this process's id and a random suffix, so a
2238
2350
  * half-written directory is never mistaken for a published payload.
@@ -2277,6 +2389,27 @@ function cacheRoot(env = process.env) {
2277
2389
  return join(resolveDshHome(env), ...CACHE_DIR_PARTS);
2278
2390
  }
2279
2391
  /**
2392
+ * Absolute root of the isolated fallback payload cache.
2393
+ *
2394
+ * The DSH home is a data tree a workspace sandbox may have labelled Low with
2395
+ * an inheritable ACE. A copy published below it then inherits that label and
2396
+ * starts a Low-integrity bash, which cannot write a Medium workspace or temp
2397
+ * directory. This root deliberately lives OUTSIDE the DSH home, under the
2398
+ * per-user application-data (or cache) directory instead.
2399
+ *
2400
+ * It still follows the probe-isolation convention: the final path component is
2401
+ * derived from the DSH home, so an isolated `DSH_HOME` gets its own isolated
2402
+ * cache too. Operators whose application-data tree is itself labelled Low can
2403
+ * point {@link RUNTIME_ROOT_ENV} at a directory they have verified.
2404
+ * @param env - environment to read the override, app-data root and DSH home from.
2405
+ * @returns the directory the fallback payload copies are published under.
2406
+ */
2407
+ function isolatedCacheRoot(env = process.env) {
2408
+ const override = env[RUNTIME_ROOT_ENV]?.trim();
2409
+ if (override !== void 0 && override !== "") return resolve(override);
2410
+ return join(env.LOCALAPPDATA ?? (process.platform === "win32" ? join(homedir(), "AppData", "Local") : env.XDG_CACHE_HOME ?? join(homedir(), ".cache")), ...ISOLATED_CACHE_DIR_PARTS, sha256(resolveDshHome(env)).slice(0, 12));
2411
+ }
2412
+ /**
2280
2413
  * Parse a sha256sum-style manifest: '<64 hex> <path>' per line. Blank lines
2281
2414
  * and '#' comments are skipped, so the file stays a valid 'sha256sum -c'
2282
2415
  * input while carrying a human-readable header.
@@ -2455,10 +2588,11 @@ function removeStaging(staging) {
2455
2588
  *
2456
2589
  * The copy's own manifest must reproduce the expected key before any byte is
2457
2590
  * executed, so a directory whose manifest was rewritten alongside its files is
2458
- * a miss rather than a match.
2591
+ * a miss rather than a match. This is a BYTE check only: it says nothing about
2592
+ * the security descriptor, which is why callers also run {@link cacheSafe}.
2459
2593
  * @param root - the candidate payload root.
2460
2594
  * @param key - the key the shipped manifest produced.
2461
- * @returns whether that directory can be spawned from.
2595
+ * @returns whether that directory's bytes can be spawned from.
2462
2596
  */
2463
2597
  function cacheReady(root, key) {
2464
2598
  try {
@@ -2471,6 +2605,29 @@ function cacheReady(root, key) {
2471
2605
  }
2472
2606
  }
2473
2607
  /**
2608
+ * Whether a published tree's mandatory integrity label is safe to spawn from.
2609
+ *
2610
+ * Both the directory and the executable itself are inspected: the Windows
2611
+ * sandbox applies an inheritable Low ACE to the directory, and the image then
2612
+ * carries an inherited Low ACE. Before a directory exists, the closest existing
2613
+ * ancestor is what decides the label a newly created file inherits.
2614
+ *
2615
+ * `unknown` is not treated as safe. A descriptor we cannot read cannot be
2616
+ * claimed as verified, so the caller moves on to another candidate root rather
2617
+ * than silently running from an unverified image.
2618
+ * @param root - the candidate payload root.
2619
+ * @param readLabel - the label reader (injectable seam).
2620
+ * @returns the label verdict for that tree.
2621
+ */
2622
+ function cacheSafe(root, readLabel) {
2623
+ const verdicts = existingAncestors(root).map((target) => readLabel(target));
2624
+ const bash = bashIn(root);
2625
+ if (existsSync(bash)) verdicts.push(readLabel(bash));
2626
+ if (verdicts.includes("low-or-untrusted")) return "low-or-untrusted";
2627
+ if (verdicts.includes("unknown")) return "unknown";
2628
+ return "medium-or-higher";
2629
+ }
2630
+ /**
2474
2631
  * Publish one payload copy under its key.
2475
2632
  *
2476
2633
  * The copy is built in a staging directory beside the target and renamed into
@@ -2501,18 +2658,28 @@ function publishPayload(source, target, key, copy) {
2501
2658
  /**
2502
2659
  * Resolve the shell one host runs, publishing the payload outside the package.
2503
2660
  *
2504
- * The verification order is the whole point: the shipped manifest identifies
2505
- * the payload, a published copy of that identity is reused when it verifies,
2506
- * and otherwise the packaged tree is verified first and only then copied. What
2507
- * gets spawned is therefore always a tree whose bytes match the shipped
2508
- * manifest, and it lives under the DSH home where an update or uninstall of
2509
- * this package cannot be blocked by a running shell.
2661
+ * Two independent proofs gate every tree that can be spawned: the shipped
2662
+ * SHA256 manifest proves its BYTES, and a mandatory-integrity-label check
2663
+ * proves its SECURITY DESCRIPTOR cannot downgrade a Medium runner to a Low
2664
+ * process. A label check runs before a published copy is reused, before a new
2665
+ * copy is published, and again after publication (the decisive check is on the
2666
+ * bash.exe that will actually be spawned). A tree carrying Low or Untrusted is
2667
+ * never reused and never spawned from, so a hash match alone can no longer keep
2668
+ * a broken cache alive across restarts and updates.
2669
+ *
2670
+ * Candidate roots are tried in order. The DSH home cache keeps the #1996 fix;
2671
+ * when its data tree is labelled Low, the payload is published into an isolated
2672
+ * per-user application-data root instead, still OUTSIDE the package. An old Low
2673
+ * cache under the DSH home is therefore migrated by abandonment, not by a
2674
+ * one-off repair of one payload-key directory.
2510
2675
  *
2511
- * A cache that cannot be written is not a reason to withhold the tool: the
2512
- * verified packaged tree runs instead and the caller is told, through
2513
- * {@link PrepareRuntimeOptions.warn}, that updates will need this host stopped.
2514
- * A payload that fails its manifest is still a refusal — running unverified
2515
- * bytes is the outcome the manifest exists to prevent, cache or no cache.
2676
+ * When no candidate can be written or verified, the verified packaged tree runs
2677
+ * instead and the caller is told, through {@link PrepareRuntimeOptions.warn},
2678
+ * that updates will need this host stopped. But if a Low label was observed and
2679
+ * even the packaged image is not proven clean, the mount is REFUSED with
2680
+ * `unsafe-integrity` rather than silently executing a shell that cannot write
2681
+ * the session's workspace. A payload that fails its manifest is always a
2682
+ * refusal, cache or no cache.
2516
2683
  * @param options - host facts, roots, and the seams tests drive.
2517
2684
  * @returns the shell paths to run, or the rejection reason.
2518
2685
  */
@@ -2525,8 +2692,20 @@ function prepareRuntime(options = {}) {
2525
2692
  if (refused !== void 0) return refused;
2526
2693
  const packageRoot = options.packageRoot ?? PACKAGE_ROOT;
2527
2694
  const source = runtimeRoot(packageRoot);
2528
- const cacheDir = options.cacheRoot ?? cacheRoot(options.env);
2529
2695
  const warn = options.warn ?? (() => {});
2696
+ const rawLabel = options.readLabel ?? readMandatoryLabel;
2697
+ const labels = /* @__PURE__ */ new Map();
2698
+ const readLabel = (target) => {
2699
+ const hit = labels.get(target);
2700
+ if (hit !== void 0) return hit;
2701
+ const verdict = rawLabel(target);
2702
+ labels.set(target, verdict);
2703
+ return verdict;
2704
+ };
2705
+ const copy = options.copy ?? copyTree;
2706
+ const roots = [options.cacheRoot ?? cacheRoot(options.env)];
2707
+ const isolated = options.isolatedCacheRoot ?? (options.cacheRoot === void 0 ? isolatedCacheRoot(options.env) : void 0);
2708
+ if (isolated !== void 0 && !roots.includes(isolated)) roots.push(isolated);
2530
2709
  let key;
2531
2710
  try {
2532
2711
  key = payloadKey(parseChecksums(readFileSync(join(source, CHECKSUM_FILE), "utf8")));
@@ -2536,21 +2715,69 @@ function prepareRuntime(options = {}) {
2536
2715
  message: "the payload checksum manifest could not be read: " + describe(error)
2537
2716
  };
2538
2717
  }
2539
- const published = join(cacheDir, key);
2540
- if (cacheReady(published, key)) return readyFrom(published, "cache");
2541
- const shipped = resolveRuntime(host, packageRoot);
2542
- if ("code" in shipped) return shipped;
2543
- try {
2544
- publishPayload(source, published, key, options.copy ?? copyTree);
2545
- } catch (error) {
2546
- warn("the verified payload could not be published to " + published + " (" + describe(error) + "), so this host runs the shell from " + source + "; while it runs, updating or uninstalling this package can fail with ERR_PNPM_EPERM");
2718
+ const diagnoses = [];
2719
+ let shipped;
2720
+ const verifiedPackage = () => {
2721
+ shipped ??= resolveRuntime(host, packageRoot);
2547
2722
  return shipped;
2548
- }
2549
- if (!cacheReady(published, key)) {
2550
- warn("the payload copy at " + published + " did not verify against the shipped manifest, so this host runs the shell from " + source + "; while it runs, updating or uninstalling this package can fail with ERR_PNPM_EPERM");
2551
- return shipped;
2552
- }
2553
- return readyFrom(published, "cache");
2723
+ };
2724
+ for (const cacheDir of roots) {
2725
+ const published = join(cacheDir, key);
2726
+ const before = cacheSafe(published, readLabel);
2727
+ if (before === "low-or-untrusted") {
2728
+ diagnoses.push({
2729
+ low: true,
2730
+ message: "the cache root " + cacheDir + " carries a Low or Untrusted mandatory integrity label"
2731
+ });
2732
+ continue;
2733
+ }
2734
+ if (before === "unknown") {
2735
+ diagnoses.push({
2736
+ low: false,
2737
+ message: "the mandatory integrity label of " + cacheDir + " could not be read"
2738
+ });
2739
+ continue;
2740
+ }
2741
+ if (cacheReady(published, key)) return readyFrom(published, "cache");
2742
+ const packaged = verifiedPackage();
2743
+ if ("code" in packaged) return packaged;
2744
+ try {
2745
+ publishPayload(source, published, key, copy);
2746
+ } catch (error) {
2747
+ diagnoses.push({
2748
+ low: false,
2749
+ message: "the verified payload could not be published to " + published + " (" + describe(error) + ")"
2750
+ });
2751
+ continue;
2752
+ }
2753
+ if (!cacheReady(published, key)) {
2754
+ diagnoses.push({
2755
+ low: false,
2756
+ message: "the payload copy at " + published + " did not verify against the shipped manifest"
2757
+ });
2758
+ continue;
2759
+ }
2760
+ const after = cacheSafe(published, readLabel);
2761
+ if (after !== "medium-or-higher") {
2762
+ diagnoses.push({
2763
+ low: after === "low-or-untrusted",
2764
+ message: after === "low-or-untrusted" ? "the newly published bash.exe at " + bashIn(published) + " inherited a Low or Untrusted mandatory integrity label" : "the mandatory integrity label of the newly published bash.exe at " + bashIn(published) + " could not be read"
2765
+ });
2766
+ continue;
2767
+ }
2768
+ return readyFrom(published, "cache");
2769
+ }
2770
+ const packaged = verifiedPackage();
2771
+ if ("code" in packaged) return packaged;
2772
+ const reasons = diagnoses.map((entry) => entry.message).join("; ");
2773
+ const sawLow = diagnoses.some((entry) => entry.low);
2774
+ const packagedLabel = readLabel(bashPath(packageRoot));
2775
+ if (sawLow && packagedLabel === "low-or-untrusted") return {
2776
+ code: "unsafe-integrity",
2777
+ message: "every runtime cache root is unsafe to spawn from and the packaged payload is not proven clean: " + reasons + ". A Low-labelled bash.exe would start a Low-integrity process on this Medium host, which cannot write an ordinary workspace or temp directory, so win_bash refuses to mount instead of silently running a broken shell. Use the host pwsh tool, or point DSH_WIN_BASH_RUNTIME_HOME at a directory you have verified has no Low Mandatory Level label. Do not lower the workspace integrity level or change the global sandbox policy to work around this."
2778
+ };
2779
+ warn(reasons + ", so this host runs the shell from " + source + "; while it runs, updating or uninstalling this package can fail with ERR_PNPM_EPERM");
2780
+ return packaged;
2554
2781
  }
2555
2782
  //#endregion
2556
2783
  //#region src/background.ts
@@ -3155,4 +3382,4 @@ function apply(ctx, config) {
3155
3382
  });
3156
3383
  }
3157
3384
  //#endregion
3158
- export { BACKGROUND_JOB_KIND, CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, DEFAULT_SYNC_WITH_LIANGSHEN, GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, HOST_PWSH_TOOL, LIANGSHEN_PRESET_ID, SERVING_MODE, SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashIn, bashPath, binIn, buildFrame, cacheRoot, declaresLiangShen, gateRefusalMessage, inject, installPwshReplacement, markerFor, mountWithGate, name, parseChecksums, parseFrame, payloadKey, prepareRuntime, readJobRegistry, readPresetRegistry, registerWinBash, removeShellTempDir, renderResult, resolveRuntime, runtimeRoot, settleHostTree, shIn, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, startLiangShenGate, stripTerminalEscapes, sweepOrphanShellTempDirs, truncationNotice, validateConfig, verifyPayload, verifyPayloadRoot };
3385
+ export { BACKGROUND_JOB_KIND, CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, CONFIG_DEFAULTS, Config, DEFAULT_DESCRIPTION, DEFAULT_ENABLE_RUN_IN_BACKGROUND, DEFAULT_REPLACE_PWSH, DEFAULT_SYNC_WITH_LIANGSHEN, GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, HOST_PWSH_TOOL, ISOLATED_CACHE_DIR_PARTS, LIANGSHEN_PRESET_ID, RUNTIME_ROOT_ENV, SERVING_MODE, SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, WIN_BASH_TOOL, apply, bashIn, bashPath, binIn, buildFrame, cacheRoot, declaresLiangShen, gateRefusalMessage, inject, installPwshReplacement, isolatedCacheRoot, markerFor, mountWithGate, name, parseChecksums, parseFrame, payloadKey, prepareRuntime, readJobRegistry, readPresetRegistry, registerWinBash, removeShellTempDir, renderResult, resolveRuntime, runtimeRoot, settleHostTree, shIn, shPath, shellArgv, shellEnvironment, shellTempDir, startBackgroundJob, startLiangShenGate, stripTerminalEscapes, sweepOrphanShellTempDirs, truncationNotice, validateConfig, verifyPayload, verifyPayloadRoot };
@@ -15,7 +15,7 @@
15
15
  * STRUCTURALLY: a leaf plugin takes no dependency on @deepseek-ai/dsh-jobs to
16
16
  * call one method on an optional service, and the same decision keeps this
17
17
  * package out of the job registry's implementation. The members below are
18
- * mirrored from the published declaration of @deepseek-ai/dsh-jobs@0.2.1-rc.3:
18
+ * mirrored from the published declaration of @deepseek-ai/dsh-jobs@0.2.2-rc.1:
19
19
  *
20
20
  * lib/types/index.d.ts
21
21
  * abstract class JobRegistry {
@@ -12,7 +12,7 @@
12
12
  * on @deepseek-ai/dsh-agent-preset-registry (a leaf plugin takes no SDK
13
13
  * dependency to read one optional service), so the single method consumed is
14
14
  * mirrored from the published declaration of
15
- * @deepseek-ai/dsh-agent-preset-registry@0.2.1-rc.3, lib/types/index.d.ts:
15
+ * @deepseek-ai/dsh-agent-preset-registry@0.2.2-rc.1, lib/types/index.d.ts:
16
16
  *
17
17
  * export declare class AgentPresetRegistry {
18
18
  * list(): Promise<AgentPreset[]>
@@ -13,14 +13,17 @@
13
13
  * and on a Windows host that is not x64, because no PATH bash is ever used as
14
14
  * a substitute.
15
15
  *
16
- * Mount-time publication: the tree that is spawned is a verified copy under the
17
- * DSH home, not the tree inside this package. A persistent shell holds its own
18
- * executable open, and Windows refuses to rename a directory that holds a
19
- * running executable, so a shell started inside node_modules makes pnpm's
16
+ * Mount-time publication: the tree that is spawned is a verified copy outside
17
+ * this package, not the tree inside node_modules. A persistent shell holds its
18
+ * own executable open, and Windows refuses to rename a directory that holds a
19
+ * running executable, so a shell started inside the package makes pnpm's
20
20
  * import of this package fail with ERR_PNPM_EPERM. Publishing the payload
21
21
  * outside the package is what lets an update or uninstall run while sessions
22
- * are live; a cache that cannot be written keeps the tool working from the
23
- * packaged tree and logs that updates will need this host stopped.
22
+ * are live. The copy's mandatory integrity label is checked before reuse and
23
+ * before execution: a Low-labelled cache is abandoned for an isolated root
24
+ * instead of starting a Low-integrity shell. A cache that cannot be written,
25
+ * or no safe root at all, keeps the tool working from the packaged tree and
26
+ * logs that updates will need this host stopped.
24
27
  *
25
28
  * Availability gate: win_bash serves sessions that run the LiangShen (梁神)
26
29
  * preset, so its registration follows that preset's DECLARATION in the
@@ -61,7 +64,7 @@ export type { RenderFacts } from './tool.ts';
61
64
  export { SHELL_TEMP_PREFIX, ShellRegistry, ShellUnavailableError, removeShellTempDir, shellArgv, shellEnvironment, shellTempDir, sweepOrphanShellTempDirs, type ShellTempSweep, type ShellTempSweepOptions, } from './shell.ts';
62
65
  export { buildFrame, markerFor, parseFrame } from './protocol.ts';
63
66
  export { GATE_DECLARATION_WAIT_MS, GATE_POLL_INTERVAL_MS, GATE_READ_TIMEOUT_MS, GATE_SETTLE_TIMEOUT_MS, LIANGSHEN_PRESET_ID, declaresLiangShen, readPresetRegistry, settleHostTree, startLiangShenGate, type GateOptions, type GateOutcome, type GateReason, type PresetRosterReader, type PresetRosterRow, type SettleStatus, } from './gate.ts';
64
- export { CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, bashIn, bashPath, binIn, cacheRoot, parseChecksums, payloadKey, prepareRuntime, resolveRuntime, runtimeRoot, shIn, shPath, verifyPayload, verifyPayloadRoot, type CopyTree, type PrepareRuntimeOptions, } from './runtime.ts';
67
+ export { CACHE_DIR_PARTS, CACHE_STAGING_PREFIX, ISOLATED_CACHE_DIR_PARTS, RUNTIME_ROOT_ENV, bashIn, bashPath, binIn, cacheRoot, isolatedCacheRoot, parseChecksums, payloadKey, prepareRuntime, resolveRuntime, runtimeRoot, shIn, shPath, verifyPayload, verifyPayloadRoot, type CopyTree, type PrepareRuntimeOptions, } from './runtime.ts';
65
68
  /** Cordis plugin name; also the loader row id this package mounts under. */
66
69
  export declare const name = "dsh-win-bash";
67
70
  /** Required services: the tool registry and the managed subprocess seam. */
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Windows mandatory-integrity-label inspection for the published payload cache.
3
+ *
4
+ * A cache under a data tree that carries an inheritable Low Mandatory Level ACE
5
+ * produces a bash.exe that inherits that label. Windows then starts a
6
+ * Low-integrity process even from a Medium-integrity runner
7
+ * (TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN takes the LOWER of parent token and
8
+ * executable image), and a Low process cannot write an ordinary Medium
9
+ * workspace or temp directory. The bytes and SHA256 manifest are identical, so
10
+ * a checksum-only cache check cannot see this: the defect is in the security
11
+ * descriptor, not the file content.
12
+ *
13
+ * Node's fs API cannot read a SACL. The Windows built-in `icacls <path> /save`
14
+ * writes a security descriptor as language-independent SDDL in UTF-16LE;
15
+ * `S:...` carries the mandatory label ACEs, e.g. `(ML;OICI;NW;;;LW)` for an
16
+ * inheritable Low label or `(ML;ID;NW;;;LW)` for an inherited one. `LW` is
17
+ * the SDDL abbreviation of S-1-16-4096 (Low); Untrusted is S-1-16-0. Anything
18
+ * below Medium (S-1-16-8192) can downgrade the spawned shell.
19
+ *
20
+ * The binary is addressed by absolute path under SystemRoot, never through
21
+ * PATH. This module only reads; it never changes a label, a DACL, a token or a
22
+ * user's data directory.
23
+ * @module @linxin666/dsh-win-bash/integrity
24
+ */
25
+ /** Integrity RID of Medium; a label below it downgrades a spawned process. */
26
+ export declare const MEDIUM_INTEGRITY_RID = 8192;
27
+ /** Wall-clock bound on one icacls query for a security descriptor. */
28
+ export declare const READ_LABEL_TIMEOUT_MS = 5000;
29
+ /** What one mandatory-integrity-label inspection established. */
30
+ export type IntegrityLabel = 'medium-or-higher' | 'low-or-untrusted' | 'unknown';
31
+ /**
32
+ * A reader for one path's mandatory integrity label. The seam exists so tests
33
+ * can drive Low/Unknown verdicts without touching the host's ACLs.
34
+ */
35
+ export type LabelReader = (target: string) => IntegrityLabel;
36
+ /**
37
+ * Classify the mandatory label ACEs of one icacls /save SDDL blob.
38
+ *
39
+ * A missing SACL means the object has no explicit label and inherits Medium by
40
+ * default. High/System/Medium labels are harmless here; only Low or Untrusted
41
+ * can turn a Medium runner's child into a Low process.
42
+ * @param sddl - the UTF-16LE-decoded contents of an icacls /save file.
43
+ * @returns the label verdict. `unknown` is reserved for the reader that could
44
+ * not obtain or trust a descriptor at all; a parsed blob always decides.
45
+ */
46
+ export declare function parseIntegritySddl(sddl: string): IntegrityLabel;
47
+ /**
48
+ * Read one existing path's mandatory integrity label.
49
+ *
50
+ * On a POSIX host there is no Windows mandatory integrity control (and this
51
+ * package does not mount there), so the label cannot downgrade anything. A
52
+ * missing icacls, a failed query or an unreadable descriptor is reported as
53
+ * `unknown` rather than guessed: the caller decides whether to fall back.
54
+ * @param target - an existing file or directory to inspect.
55
+ * @param env - environment supplying SystemRoot; the live one by default.
56
+ * @returns the label verdict.
57
+ */
58
+ export declare function readMandatoryLabel(target: string, env?: NodeJS.ProcessEnv): IntegrityLabel;
59
+ /**
60
+ * The nearest existing path at or above `path`.
61
+ *
62
+ * A directory that does not exist yet has no descriptor of its own; a new file
63
+ * created below it inherits the label of the closest existing ancestor. That
64
+ * ancestor is what a pre-publication check has to inspect.
65
+ * @param path - the prospective path.
66
+ * @returns itself when it exists, otherwise its closest existing ancestor.
67
+ */
68
+ export declare function nearestExistingAncestor(path: string): string;
69
+ /** Bound on the directory chain walked, so a pathological path cannot spin. */
70
+ export declare const MAX_ANCESTOR_DEPTH = 32;
71
+ /**
72
+ * Every existing path from `path` up to the volume root.
73
+ *
74
+ * A cache root can sit several levels below the data tree that a workspace
75
+ * sandbox labelled Low, and an inheritable ACE on ANY of those ancestors can
76
+ * still be propagated onto existing children later. Checking only the nearest
77
+ * existing ancestor would miss that, so the whole chain is inspected.
78
+ * @param path - the prospective path (it need not exist yet).
79
+ * @returns the existing ancestors, nearest first.
80
+ */
81
+ export declare function existingAncestors(path: string): string[];