@linxin666/dsh-win-bash 0.4.14 → 0.4.15

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: 559766d3c5e9f89bebcd54df75c4ec1fe421e30d
6
+ README.zh.md: e5489d2b8ea51fdb53e70121410b85d3c1310b6d
package/README.md CHANGED
@@ -257,6 +257,24 @@ anything runs, and an isolated `DSH_HOME` gets its own cache. When that copy
257
257
  cannot be written, the verified packaged tree runs instead and one warning line
258
258
  says so.
259
259
 
260
+ Matching the manifest is not enough to make a copy safe to run. A Windows
261
+ mandatory integrity label lives in the file's security descriptor, not in its
262
+ bytes: a data tree carrying an inheritable Low label gives the copied
263
+ `bash.exe` a Low label, and Windows then starts a Low-integrity process even
264
+ from a Medium runner. That process cannot write an ordinary Medium workspace or
265
+ temp directory. Before a copy is reused, before one is published, and again
266
+ after publication, `win_bash` reads the mandatory labels of the directory chain
267
+ and of `bash.exe` through the Windows `icacls` SDDL output. A Low or Untrusted
268
+ tree is never reused and never spawned from; the payload is published into an
269
+ isolated per-user cache root instead (still outside the package), so a stale Low
270
+ cache is abandoned rather than kept alive across restarts and updates. This
271
+ checks metadata only: it never changes a label, a DACL or a token, and it never
272
+ asks the user to lower a workspace label, change the sandbox policy or run DSH
273
+ elevated. If no safe cache root exists, the verified packaged tree runs with an
274
+ explicit warning; only when even that image is labelled Low does the mount fail
275
+ with `unsafe-integrity` and name the `pwsh` fallback. Set
276
+ `DSH_WIN_BASH_RUNTIME_HOME` to override the isolated cache root's parent.
277
+
260
278
  ## Known limitations
261
279
 
262
280
  - Windows x64 only. The payload is a Windows MSYS2 build and the tool refuses
@@ -271,8 +289,9 @@ says so.
271
289
  - A background job is one command in one process: it has no persistent state
272
290
  across jobs, and it cannot be promoted from a running foreground call
273
291
  (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
292
+ - The published payload normally lives under `<DSH_HOME>/win-bash/runtime/`,
293
+ and in the isolated per-user cache root when that data tree is labelled Low.
294
+ Each distinct payload keeps one directory there, about 16 MiB, and such a
276
295
  directory can be deleted while DSH is stopped: the next mount publishes it
277
296
  again.
278
297
 
package/README.zh.md CHANGED
@@ -210,6 +210,18 @@ shell、其 userland 以及精确的 DLL 闭包。同一 release 的两份资产
210
210
  的发布会复用已有副本,字节与清单不符的副本会在运行之前被重建,独立的 `DSH_HOME`
211
211
  得到自己的缓存。副本写不出来时,改由校验过的包内树运行,并有一条警告说明这一点。
212
212
 
213
+ 清单匹配还不足以让副本「可以运行」。Windows 强制性完整性标签在文件的安全描述符里,
214
+ 不在字节里:数据树带可继承的 Low 标签时,复制出的 `bash.exe` 也带 Low 标签,于是
215
+ Windows 即使从 Medium runner 启动也会得到 Low 完整性进程,写不了普通 Medium 工作区与
216
+ 临时目录。因此 `win_bash` 在复用副本前、发布副本前、以及发布之后,都会通过 Windows
217
+ `icacls` 的 SDDL 输出核验目录链与 `bash.exe` 的强制性完整性标签。带 Low/Untrusted
218
+ 标签的树不复用、不执行;载荷改为发布到隔离的每用户缓存根(仍在包外),旧 Low 缓存
219
+ 因此被弃用,不会在重启或更新后靠哈希匹配继续存活。这里只读取元数据:不改任何标签、
220
+ DACL 或令牌,也不要求用户降低工作区标签、修改沙箱策略或提权运行 DSH。没有安全候选
221
+ 根时,改由校验过的包内树运行并给出明确警告;只有连包内映像都带 Low 标签,才以
222
+ `unsafe-integrity` 拒绝挂载并指明 `pwsh` 退路。可用 `DSH_WIN_BASH_RUNTIME_HOME`
223
+ 覆盖隔离缓存根的父目录。
224
+
213
225
  ## 已知限制
214
226
 
215
227
  - 仅支持 Windows x64。载荷是 Windows MSYS2 构建,工具在任何其它平台或架构上都拒绝
@@ -222,8 +234,9 @@ shell、其 userland 以及精确的 DLL 闭包。同一 release 的两份资产
222
234
  字节,以及在 provider 留下 spill 文件时完整流在哪里。
223
235
  - 后台任务是「一个进程执行一条命令」:任务之间没有持久状态,也不能由正在跑的前台调用
224
236
  「升级」而来(前台调用到达 `timeoutMs` 时仍然会停掉它的 shell)。
225
- - 发布的载荷位于 `<DSH_HOME>/win-bash/runtime/`。每一份不同的载荷在那里保留一个
226
- 目录(约 16 MiB),DSH 停止时可以安全删除它:下一次挂载会重新发布。
237
+ - 发布的载荷通常位于 `<DSH_HOME>/win-bash/runtime/`;当该数据树带 Low 标签时,
238
+ 改放在隔离的每用户缓存根。每一份不同的载荷在那里保留一个目录(约 16 MiB),DSH
239
+ 停止时可以安全删除它:下一次挂载会重新发布。
227
240
 
228
241
  ## 后续工作
229
242
 
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;
@@ -2183,6 +2184,97 @@ function resolveDshHome(env = process.env, home = homedir()) {
2183
2184
  }
2184
2185
  return j(home, ".dsh");
2185
2186
  }
2187
+ /** Wall-clock bound on one icacls query for a security descriptor. */
2188
+ const READ_LABEL_TIMEOUT_MS = 5e3;
2189
+ /** One mandatory-label ACE inside an SDDL SACL: (ML;flags;rights;;;SID). */
2190
+ const MANDATORY_LABEL_ACE = /\(ML;[^)]*;([^;)]+)\)/gi;
2191
+ /**
2192
+ * Classify the mandatory label ACEs of one icacls /save SDDL blob.
2193
+ *
2194
+ * A missing SACL means the object has no explicit label and inherits Medium by
2195
+ * default. High/System/Medium labels are harmless here; only Low or Untrusted
2196
+ * can turn a Medium runner's child into a Low process.
2197
+ * @param sddl - the UTF-16LE-decoded contents of an icacls /save file.
2198
+ * @returns the label verdict. `unknown` is reserved for the reader that could
2199
+ * not obtain or trust a descriptor at all; a parsed blob always decides.
2200
+ */
2201
+ function parseIntegritySddl(sddl) {
2202
+ const sacl = /S:([^\r\n]*)/.exec(sddl)?.[1] ?? "";
2203
+ for (const match of sacl.matchAll(MANDATORY_LABEL_ACE)) {
2204
+ const sid = (match[1] ?? "").trim().toUpperCase();
2205
+ if (sid === "LW") return "low-or-untrusted";
2206
+ const numeric = /^S-1-16-(\d+)$/.exec(sid);
2207
+ if (numeric !== null && Number(numeric[1]) < 8192) return "low-or-untrusted";
2208
+ }
2209
+ return "medium-or-higher";
2210
+ }
2211
+ /** Absolute path of the Windows icacls binary, never resolved through PATH. */
2212
+ function icaclsPath(env) {
2213
+ return join(env.SystemRoot ?? env.windir ?? "C:\\Windows", "System32", "icacls.exe");
2214
+ }
2215
+ /**
2216
+ * Read one existing path's mandatory integrity label.
2217
+ *
2218
+ * On a POSIX host there is no Windows mandatory integrity control (and this
2219
+ * package does not mount there), so the label cannot downgrade anything. A
2220
+ * missing icacls, a failed query or an unreadable descriptor is reported as
2221
+ * `unknown` rather than guessed: the caller decides whether to fall back.
2222
+ * @param target - an existing file or directory to inspect.
2223
+ * @param env - environment supplying SystemRoot; the live one by default.
2224
+ * @returns the label verdict.
2225
+ */
2226
+ function readMandatoryLabel(target, env = process.env) {
2227
+ if (process.platform !== "win32") return "medium-or-higher";
2228
+ const exe = icaclsPath(env);
2229
+ if (!existsSync(exe)) return "unknown";
2230
+ let scratch;
2231
+ let aclFile;
2232
+ try {
2233
+ scratch = mkdtempSync(join(tmpdir(), "dsh-win-bash-acl-"));
2234
+ aclFile = join(scratch, "acl-" + randomUUID().slice(0, 8) + ".txt");
2235
+ const run = spawnSync(exe, [
2236
+ target,
2237
+ "/save",
2238
+ aclFile
2239
+ ], {
2240
+ windowsHide: true,
2241
+ timeout: READ_LABEL_TIMEOUT_MS,
2242
+ stdio: "ignore"
2243
+ });
2244
+ if (run.error !== void 0 || run.status !== 0 || !existsSync(aclFile)) return "unknown";
2245
+ return parseIntegritySddl(readFileSync(aclFile).toString("utf16le"));
2246
+ } catch {
2247
+ return "unknown";
2248
+ } finally {
2249
+ if (aclFile !== void 0) try {
2250
+ unlinkSync(aclFile);
2251
+ } catch {}
2252
+ if (scratch !== void 0) try {
2253
+ rmdirSync(scratch);
2254
+ } catch {}
2255
+ }
2256
+ }
2257
+ /**
2258
+ * Every existing path from `path` up to the volume root.
2259
+ *
2260
+ * A cache root can sit several levels below the data tree that a workspace
2261
+ * sandbox labelled Low, and an inheritable ACE on ANY of those ancestors can
2262
+ * still be propagated onto existing children later. Checking only the nearest
2263
+ * existing ancestor would miss that, so the whole chain is inspected.
2264
+ * @param path - the prospective path (it need not exist yet).
2265
+ * @returns the existing ancestors, nearest first.
2266
+ */
2267
+ function existingAncestors(path) {
2268
+ const found = [];
2269
+ let current = resolve(path);
2270
+ for (let depth = 0; depth < 32; depth += 1) {
2271
+ if (existsSync(current)) found.push(current);
2272
+ const parent = dirname(current);
2273
+ if (parent === current) break;
2274
+ current = parent;
2275
+ }
2276
+ return found;
2277
+ }
2186
2278
  //#endregion
2187
2279
  //#region src/runtime.ts
2188
2280
  /**
@@ -2192,7 +2284,7 @@ function resolveDshHome(env = process.env, home = homedir()) {
2192
2284
  * The package ships its own Git for Windows MinGit extraction under
2193
2285
  * runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
2194
2286
  * (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
2287
+ * point of vendoring is a shell whose version and bytes are pinned. Four
2196
2288
  * invariants implement that:
2197
2289
  *
2198
2290
  * 1. the binary is addressed by absolute path, never by name,
@@ -2200,6 +2292,13 @@ function resolveDshHome(env = process.env, home = homedir()) {
2200
2292
  * packaging time before it is used at all, and
2201
2293
  * 3. the tree that RUNS is a published copy under the DSH home, not the tree
2202
2294
  * inside the package.
2295
+ * 4. the copy's Windows mandatory integrity label is checked before it is
2296
+ * reused or before a freshly published copy is spawned. A Low (or lower)
2297
+ * label on the executable image makes Windows start a Low-integrity process
2298
+ * even from a Medium runner, and that process cannot write an ordinary
2299
+ * Medium workspace or temp directory. Such a tree is never used: the payload
2300
+ * is published into an isolated cache root instead, and if no candidate root
2301
+ * is safe the mount is refused with a specific diagnosis.
2203
2302
  *
2204
2303
  * The third invariant is why this module publishes a cache: Windows refuses to
2205
2304
  * rename a directory whose executable is running, and pnpm imports a package by
@@ -2233,6 +2332,18 @@ const CHECKSUM_FILE = "checksums.sha256";
2233
2332
  */
2234
2333
  const CACHE_DIR_PARTS = ["win-bash", "runtime"];
2235
2334
  /**
2335
+ * Directory parts of the isolated fallback cache, used only when the preferred
2336
+ * cache root carries a Low mandatory integrity label. It lives outside the DSH
2337
+ * data tree, which a workspace sandbox can label Low with an inheritable ACE.
2338
+ */
2339
+ const ISOLATED_CACHE_DIR_PARTS = ["dsh-win-bash", "runtime"];
2340
+ /**
2341
+ * Optional environment override for the isolated cache root's parent. An
2342
+ * operator whose local app data is itself labelled Low can point this at a
2343
+ * directory they have verified is Medium; it is not needed on a normal host.
2344
+ */
2345
+ const RUNTIME_ROOT_ENV = "DSH_WIN_BASH_RUNTIME_HOME";
2346
+ /**
2236
2347
  * Name prefix of the staging directory one cache copy is built in. The rest of
2237
2348
  * the name is the payload key, this process's id and a random suffix, so a
2238
2349
  * half-written directory is never mistaken for a published payload.
@@ -2277,6 +2388,27 @@ function cacheRoot(env = process.env) {
2277
2388
  return join(resolveDshHome(env), ...CACHE_DIR_PARTS);
2278
2389
  }
2279
2390
  /**
2391
+ * Absolute root of the isolated fallback payload cache.
2392
+ *
2393
+ * The DSH home is a data tree a workspace sandbox may have labelled Low with
2394
+ * an inheritable ACE. A copy published below it then inherits that label and
2395
+ * starts a Low-integrity bash, which cannot write a Medium workspace or temp
2396
+ * directory. This root deliberately lives OUTSIDE the DSH home, under the
2397
+ * per-user application-data (or cache) directory instead.
2398
+ *
2399
+ * It still follows the probe-isolation convention: the final path component is
2400
+ * derived from the DSH home, so an isolated `DSH_HOME` gets its own isolated
2401
+ * cache too. Operators whose application-data tree is itself labelled Low can
2402
+ * point {@link RUNTIME_ROOT_ENV} at a directory they have verified.
2403
+ * @param env - environment to read the override, app-data root and DSH home from.
2404
+ * @returns the directory the fallback payload copies are published under.
2405
+ */
2406
+ function isolatedCacheRoot(env = process.env) {
2407
+ const override = env[RUNTIME_ROOT_ENV]?.trim();
2408
+ if (override !== void 0 && override !== "") return resolve(override);
2409
+ 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));
2410
+ }
2411
+ /**
2280
2412
  * Parse a sha256sum-style manifest: '<64 hex> <path>' per line. Blank lines
2281
2413
  * and '#' comments are skipped, so the file stays a valid 'sha256sum -c'
2282
2414
  * input while carrying a human-readable header.
@@ -2455,10 +2587,11 @@ function removeStaging(staging) {
2455
2587
  *
2456
2588
  * The copy's own manifest must reproduce the expected key before any byte is
2457
2589
  * executed, so a directory whose manifest was rewritten alongside its files is
2458
- * a miss rather than a match.
2590
+ * a miss rather than a match. This is a BYTE check only: it says nothing about
2591
+ * the security descriptor, which is why callers also run {@link cacheSafe}.
2459
2592
  * @param root - the candidate payload root.
2460
2593
  * @param key - the key the shipped manifest produced.
2461
- * @returns whether that directory can be spawned from.
2594
+ * @returns whether that directory's bytes can be spawned from.
2462
2595
  */
2463
2596
  function cacheReady(root, key) {
2464
2597
  try {
@@ -2471,6 +2604,29 @@ function cacheReady(root, key) {
2471
2604
  }
2472
2605
  }
2473
2606
  /**
2607
+ * Whether a published tree's mandatory integrity label is safe to spawn from.
2608
+ *
2609
+ * Both the directory and the executable itself are inspected: the Windows
2610
+ * sandbox applies an inheritable Low ACE to the directory, and the image then
2611
+ * carries an inherited Low ACE. Before a directory exists, the closest existing
2612
+ * ancestor is what decides the label a newly created file inherits.
2613
+ *
2614
+ * `unknown` is not treated as safe. A descriptor we cannot read cannot be
2615
+ * claimed as verified, so the caller moves on to another candidate root rather
2616
+ * than silently running from an unverified image.
2617
+ * @param root - the candidate payload root.
2618
+ * @param readLabel - the label reader (injectable seam).
2619
+ * @returns the label verdict for that tree.
2620
+ */
2621
+ function cacheSafe(root, readLabel) {
2622
+ const verdicts = existingAncestors(root).map((target) => readLabel(target));
2623
+ const bash = bashIn(root);
2624
+ if (existsSync(bash)) verdicts.push(readLabel(bash));
2625
+ if (verdicts.includes("low-or-untrusted")) return "low-or-untrusted";
2626
+ if (verdicts.includes("unknown")) return "unknown";
2627
+ return "medium-or-higher";
2628
+ }
2629
+ /**
2474
2630
  * Publish one payload copy under its key.
2475
2631
  *
2476
2632
  * The copy is built in a staging directory beside the target and renamed into
@@ -2501,18 +2657,28 @@ function publishPayload(source, target, key, copy) {
2501
2657
  /**
2502
2658
  * Resolve the shell one host runs, publishing the payload outside the package.
2503
2659
  *
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.
2660
+ * Two independent proofs gate every tree that can be spawned: the shipped
2661
+ * SHA256 manifest proves its BYTES, and a mandatory-integrity-label check
2662
+ * proves its SECURITY DESCRIPTOR cannot downgrade a Medium runner to a Low
2663
+ * process. A label check runs before a published copy is reused, before a new
2664
+ * copy is published, and again after publication (the decisive check is on the
2665
+ * bash.exe that will actually be spawned). A tree carrying Low or Untrusted is
2666
+ * never reused and never spawned from, so a hash match alone can no longer keep
2667
+ * a broken cache alive across restarts and updates.
2668
+ *
2669
+ * Candidate roots are tried in order. The DSH home cache keeps the #1996 fix;
2670
+ * when its data tree is labelled Low, the payload is published into an isolated
2671
+ * per-user application-data root instead, still OUTSIDE the package. An old Low
2672
+ * cache under the DSH home is therefore migrated by abandonment, not by a
2673
+ * one-off repair of one payload-key directory.
2510
2674
  *
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.
2675
+ * When no candidate can be written or verified, the verified packaged tree runs
2676
+ * instead and the caller is told, through {@link PrepareRuntimeOptions.warn},
2677
+ * that updates will need this host stopped. But if a Low label was observed and
2678
+ * even the packaged image is not proven clean, the mount is REFUSED with
2679
+ * `unsafe-integrity` rather than silently executing a shell that cannot write
2680
+ * the session's workspace. A payload that fails its manifest is always a
2681
+ * refusal, cache or no cache.
2516
2682
  * @param options - host facts, roots, and the seams tests drive.
2517
2683
  * @returns the shell paths to run, or the rejection reason.
2518
2684
  */
@@ -2525,8 +2691,20 @@ function prepareRuntime(options = {}) {
2525
2691
  if (refused !== void 0) return refused;
2526
2692
  const packageRoot = options.packageRoot ?? PACKAGE_ROOT;
2527
2693
  const source = runtimeRoot(packageRoot);
2528
- const cacheDir = options.cacheRoot ?? cacheRoot(options.env);
2529
2694
  const warn = options.warn ?? (() => {});
2695
+ const rawLabel = options.readLabel ?? readMandatoryLabel;
2696
+ const labels = /* @__PURE__ */ new Map();
2697
+ const readLabel = (target) => {
2698
+ const hit = labels.get(target);
2699
+ if (hit !== void 0) return hit;
2700
+ const verdict = rawLabel(target);
2701
+ labels.set(target, verdict);
2702
+ return verdict;
2703
+ };
2704
+ const copy = options.copy ?? copyTree;
2705
+ const roots = [options.cacheRoot ?? cacheRoot(options.env)];
2706
+ const isolated = options.isolatedCacheRoot ?? (options.cacheRoot === void 0 ? isolatedCacheRoot(options.env) : void 0);
2707
+ if (isolated !== void 0 && !roots.includes(isolated)) roots.push(isolated);
2530
2708
  let key;
2531
2709
  try {
2532
2710
  key = payloadKey(parseChecksums(readFileSync(join(source, CHECKSUM_FILE), "utf8")));
@@ -2536,21 +2714,69 @@ function prepareRuntime(options = {}) {
2536
2714
  message: "the payload checksum manifest could not be read: " + describe(error)
2537
2715
  };
2538
2716
  }
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");
2717
+ const diagnoses = [];
2718
+ let shipped;
2719
+ const verifiedPackage = () => {
2720
+ shipped ??= resolveRuntime(host, packageRoot);
2547
2721
  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");
2722
+ };
2723
+ for (const cacheDir of roots) {
2724
+ const published = join(cacheDir, key);
2725
+ const before = cacheSafe(published, readLabel);
2726
+ if (before === "low-or-untrusted") {
2727
+ diagnoses.push({
2728
+ low: true,
2729
+ message: "the cache root " + cacheDir + " carries a Low or Untrusted mandatory integrity label"
2730
+ });
2731
+ continue;
2732
+ }
2733
+ if (before === "unknown") {
2734
+ diagnoses.push({
2735
+ low: false,
2736
+ message: "the mandatory integrity label of " + cacheDir + " could not be read"
2737
+ });
2738
+ continue;
2739
+ }
2740
+ if (cacheReady(published, key)) return readyFrom(published, "cache");
2741
+ const packaged = verifiedPackage();
2742
+ if ("code" in packaged) return packaged;
2743
+ try {
2744
+ publishPayload(source, published, key, copy);
2745
+ } catch (error) {
2746
+ diagnoses.push({
2747
+ low: false,
2748
+ message: "the verified payload could not be published to " + published + " (" + describe(error) + ")"
2749
+ });
2750
+ continue;
2751
+ }
2752
+ if (!cacheReady(published, key)) {
2753
+ diagnoses.push({
2754
+ low: false,
2755
+ message: "the payload copy at " + published + " did not verify against the shipped manifest"
2756
+ });
2757
+ continue;
2758
+ }
2759
+ const after = cacheSafe(published, readLabel);
2760
+ if (after !== "medium-or-higher") {
2761
+ diagnoses.push({
2762
+ low: after === "low-or-untrusted",
2763
+ 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"
2764
+ });
2765
+ continue;
2766
+ }
2767
+ return readyFrom(published, "cache");
2768
+ }
2769
+ const packaged = verifiedPackage();
2770
+ if ("code" in packaged) return packaged;
2771
+ const reasons = diagnoses.map((entry) => entry.message).join("; ");
2772
+ const sawLow = diagnoses.some((entry) => entry.low);
2773
+ const packagedLabel = readLabel(bashPath(packageRoot));
2774
+ if (sawLow && packagedLabel === "low-or-untrusted") return {
2775
+ code: "unsafe-integrity",
2776
+ 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."
2777
+ };
2778
+ warn(reasons + ", so this host runs the shell from " + source + "; while it runs, updating or uninstalling this package can fail with ERR_PNPM_EPERM");
2779
+ return packaged;
2554
2780
  }
2555
2781
  //#endregion
2556
2782
  //#region src/background.ts
@@ -3155,4 +3381,4 @@ function apply(ctx, config) {
3155
3381
  });
3156
3382
  }
3157
3383
  //#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 };
3384
+ 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[];