dsh-plugin-wsl-env 0.26.4 → 0.27.0

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.
Files changed (52) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/CONTRIBUTING.md +7 -4
  3. package/CONTRIBUTING.zh.md +3 -2
  4. package/README.md +1 -1
  5. package/SECURITY.md +21 -7
  6. package/SECURITY.zh.md +18 -5
  7. package/client.js +351 -48
  8. package/cordis.patch.yml +26 -10
  9. package/docs/API.md +2 -1
  10. package/docs/API.zh.md +2 -1
  11. package/docs/ARCHITECTURE.md +22 -4
  12. package/docs/ARCHITECTURE.zh.md +18 -4
  13. package/docs/CONFIGURATION.md +96 -12
  14. package/docs/CONFIGURATION.zh.md +80 -8
  15. package/docs/DIAGNOSTICS.md +22 -11
  16. package/docs/DIAGNOSTICS.zh.md +17 -9
  17. package/docs/LIMITATIONS.md +27 -4
  18. package/docs/LIMITATIONS.zh.md +20 -3
  19. package/docs/MIGRATION.md +2 -2
  20. package/docs/MIGRATION.zh.md +2 -2
  21. package/docs/QUICKSTART.md +31 -20
  22. package/docs/QUICKSTART.zh.md +16 -9
  23. package/docs/README.zh.md +1 -1
  24. package/docs/REQUIREMENTS.zh.md +3 -2
  25. package/lib/agent-confined.d.ts +9 -1
  26. package/lib/agent-confined.js +3 -3
  27. package/lib/bwrap.d.ts +16 -0
  28. package/lib/bwrap.js +9 -0
  29. package/lib/fs-routing.d.ts +3 -0
  30. package/lib/fs-routing.js +2 -0
  31. package/lib/messages.js +2 -2
  32. package/lib/plugin-update.d.ts +212 -0
  33. package/lib/plugin-update.js +283 -0
  34. package/lib/sandbox-core.d.ts +2 -0
  35. package/lib/sandbox-core.js +5 -3
  36. package/lib/session-runtime.d.ts +10 -1
  37. package/lib/session-runtime.js +3 -1
  38. package/lib/shell-env.js +1 -1
  39. package/lib/socket-isolation.d.ts +103 -0
  40. package/lib/socket-isolation.js +166 -0
  41. package/lib/status.d.ts +21 -8
  42. package/lib/status.js +53 -18
  43. package/lib/update-check.d.ts +49 -9
  44. package/lib/update-check.js +81 -28
  45. package/lib/wsl-doctor-tool.js +2 -0
  46. package/lib/wsl-filesystem.d.ts +39 -1
  47. package/lib/wsl-filesystem.js +51 -4
  48. package/lib/wsl-shell.d.ts +67 -3
  49. package/lib/wsl-shell.js +75 -12
  50. package/package.json +8 -3
  51. package/scripts/doctor.mjs +199 -3
  52. package/scripts/profile-preset.mjs +10 -2
package/lib/wsl-shell.js CHANGED
@@ -14,6 +14,7 @@ import { configureAgentBackend, ensureNativeSessionAgent } from "./native-agent.
14
14
  import { installMessagesLocale, t } from "./messages.js";
15
15
  import { defaultDistro, defaultShell, runCapture, shellArgs, workdirFailure, wslErrorCode } from "./wsl.js";
16
16
  import { validateWritableRootsConfig } from "./writable-roots.js";
17
+ import { SocketIsolationError, socketMasksFor as resolveSocketMasks } from "./socket-isolation.js";
17
18
  import { ProviderRuntimeBook, configuredCwd, distroHome, effectiveMaskWindowsDrive, effectiveWritableRoots, resolveOperationDistro, sessionRuntimeWanted } from "./provider-common.js";
18
19
  /**
19
20
  * Every model shell call gets a rebuilt managed `DSH_*` namespace (see
@@ -119,6 +120,29 @@ export class WslShellExecutor extends LocalBashExecutor {
119
120
  * read side still reaches `/mnt` through the shared read agent.
120
121
  */
121
122
  maskWindowsDrive: z.boolean().default(false),
123
+ /**
124
+ * The socket surfaces a confined COMMAND cannot reach. The sandbox's mount
125
+ * profile confines file effects, not process authority: a command can
126
+ * otherwise ask the user's systemd manager to start a unit outside the
127
+ * fence, or connect to a container daemon and start work outside it.
128
+ *
129
+ * - `off` (default) — nothing masked; the boundary is the documented
130
+ * `enforcement: partial`.
131
+ * - `session-bus` — masks `$XDG_RUNTIME_DIR/bus` and
132
+ * `$XDG_RUNTIME_DIR/systemd/private`, so `systemd-run --user` and
133
+ * `systemctl --user` fail inside the command.
134
+ * - `strict` — adds `/run/dbus/system_bus_socket` and the container
135
+ * sockets (`docker`, `podman`, `containerd`, `crio`) that exist and are
136
+ * reachable by the distro user; D-Bus and container clients inside the
137
+ * command fail.
138
+ *
139
+ * The masks are a narrowing, not a closure: same-user `/proc`, the
140
+ * interop transport and other IPC remain, and `enforcement` stays
141
+ * `partial`. The key applies to the command plane (`wsl-shell`); the
142
+ * filesystem rows' confined agent runs only this plugin's fs protocol,
143
+ * never model-authored commands. Verified by `pnpm run probe:sandbox`.
144
+ */
145
+ socketIsolation: z.union(["off", "session-bus", "strict"]).default("off"),
122
146
  /**
123
147
  * Extra directories under `workspace-write`, in distro spelling. The
124
148
  * plugin grants them together with the workspace, so toolchain caches
@@ -205,6 +229,7 @@ export class WslShellExecutor extends LocalBashExecutor {
205
229
  this.sessionRuntimeOwner = randomUUID();
206
230
  this.sessionScopeProbe = (argv) => runCapture(argv);
207
231
  this.writableRootsProbe = (argv) => runCapture(argv);
232
+ this.socketIsolationProbe = (argv) => runCapture(argv);
208
233
  // The preset realm disposes when the session ends; the scope must go with
209
234
  // it, or a dev server outlives the session that started it.
210
235
  ctx.effect(() => () => this.disposeSessionRuntimes().catch(() => { }), "wsl session runtimes");
@@ -343,14 +368,14 @@ export class WslShellExecutor extends LocalBashExecutor {
343
368
  * @param distro - the resolved distro name.
344
369
  * @returns the runtime entry, or undefined when the mode is off.
345
370
  */
346
- sessionRuntimeFor(policy, resolved, distro, writableRoots = []) {
371
+ sessionRuntimeFor(policy, resolved, distro, writableRoots = [], socketMasks = [], maskInterop = false) {
347
372
  const config = this.wslConfig;
348
373
  if (!config.sessionSandbox)
349
374
  return undefined;
350
375
  const mode = policy?.mode ?? "danger-full-access";
351
376
  const workspaceRoot = policy?.workspaceRoot ?? (configuredCwd(this.config) || resolved.workdir);
352
377
  const sessionId = policy?.sessionId || resolved.dshEnv?.DSH_SESSION_ID || this.sessionRuntimeOwner;
353
- const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode, maskWindowsDrive: effectiveMaskWindowsDrive(config), writableRoots });
378
+ const key = SessionRuntimes.key({ sessionId, distro, workspaceRoot, mode, maskWindowsDrive: effectiveMaskWindowsDrive(config), writableRoots, socketMasks, maskInterop });
354
379
  const held = this.runtimeBook.sessionRuntimeEntries.get(key);
355
380
  if (held !== undefined)
356
381
  return held;
@@ -362,6 +387,8 @@ export class WslShellExecutor extends LocalBashExecutor {
362
387
  mode,
363
388
  maskWindowsDrive: effectiveMaskWindowsDrive(config),
364
389
  writableRoots,
390
+ socketMasks,
391
+ maskInterop,
365
392
  });
366
393
  this.runtimeBook.sessionRuntimeEntries.set(key, entry);
367
394
  return entry;
@@ -680,6 +707,37 @@ export class WslShellExecutor extends LocalBashExecutor {
680
707
  run: this.writableRootsProbe,
681
708
  });
682
709
  }
710
+ /**
711
+ * The socket masks one confined command's profile binds, resolved once per
712
+ * distro from the row's `socketIsolation` stance. Empty when the sandbox is
713
+ * off, the command is unconfined, or the stance is `off`. A probe failure is
714
+ * a sandbox refusal, never an unmasked run.
715
+ *
716
+ * @param distro - the distro the command runs in.
717
+ * @param mode - the per-call file-effect mode.
718
+ * @param signal - optional cancellation for the one-time probe.
719
+ * @returns the existing socket paths to mask.
720
+ * @throws {SandboxUnavailableError} when a configured isolation cannot be resolved.
721
+ */
722
+ async socketMasksFor(distro, mode, signal) {
723
+ const config = this.wslConfig;
724
+ if (!config.sandbox || mode === undefined || mode === "danger-full-access" || config.socketIsolation === "off")
725
+ return [];
726
+ try {
727
+ return await resolveSocketMasks({
728
+ mode: config.socketIsolation,
729
+ wslPath: config.wslPath,
730
+ distro,
731
+ run: this.socketIsolationProbe,
732
+ ...(signal === undefined ? {} : { signal }),
733
+ });
734
+ }
735
+ catch (error) {
736
+ if (error instanceof SocketIsolationError)
737
+ throw new SandboxUnavailableError(mode, error.message);
738
+ throw error;
739
+ }
740
+ }
683
741
  /**
684
742
  * Execute one resolved spec inside the distro, confined by the per-call policy
685
743
  * when there is one.
@@ -700,9 +758,14 @@ export class WslShellExecutor extends LocalBashExecutor {
700
758
  const shell = await this.shellFor(distro);
701
759
  this.throwIfWorkdirInAnotherDistro(resolved.workdir, distro);
702
760
  const writableRoots = await this.writableRootsFor(distro, resolved.sandboxPolicy, resolved.signal);
761
+ const socketMasks = await this.socketMasksFor(distro, resolved.sandboxPolicy?.mode, resolved.signal);
762
+ const maskInterop = config.sandbox
763
+ && config.socketIsolation === "strict"
764
+ && resolved.sandboxPolicy !== undefined
765
+ && resolved.sandboxPolicy.mode !== "danger-full-access";
703
766
  if (config.agent) {
704
767
  try {
705
- return await this.executeViaAgent(resolved, distro, shell, writableRoots);
768
+ return await this.executeViaAgent(resolved, distro, shell, writableRoots, socketMasks, maskInterop);
706
769
  }
707
770
  catch (error) {
708
771
  // Only an out-of-service agent falls back; anything else (a cwd
@@ -711,7 +774,7 @@ export class WslShellExecutor extends LocalBashExecutor {
711
774
  throw error;
712
775
  }
713
776
  }
714
- return this.executeOneShot(resolved, distro, shell, writableRoots);
777
+ return this.executeOneShot(resolved, distro, shell, writableRoots, socketMasks, maskInterop);
715
778
  }
716
779
  /**
717
780
  * Refuse a workdir that names another WSL distro — the shell-side twin of
@@ -740,15 +803,15 @@ export class WslShellExecutor extends LocalBashExecutor {
740
803
  * @param shell - the resolved distro shell.
741
804
  * @returns the decorated execution result.
742
805
  */
743
- async executeViaAgent(resolved, distro, shell, writableRoots = []) {
806
+ async executeViaAgent(resolved, distro, shell, writableRoots = [], socketMasks = [], maskInterop = false) {
744
807
  const config = this.wslConfig;
745
808
  const policy = resolved.sandboxPolicy;
746
809
  const confined = this.sandbox !== undefined && policy !== undefined && policy.mode !== "danger-full-access"
747
- ? await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode: policy.mode }, { distro, signal: resolved.signal, writableRoots })
810
+ ? await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode: policy.mode }, { distro, signal: resolved.signal, writableRoots, socketMasks, maskInterop })
748
811
  : undefined;
749
812
  const mode = policy?.mode;
750
813
  const useScope = await this.wantsSessionRuntime(distro);
751
- const runtime = useScope ? this.sessionRuntimeFor(policy, resolved, distro, writableRoots) : undefined;
814
+ const runtime = useScope ? this.sessionRuntimeFor(policy, resolved, distro, writableRoots, socketMasks, maskInterop) : undefined;
752
815
  const agent = runtime !== undefined ? runtime.agent : await this.executionAgent(distro);
753
816
  // A session runtime's own bwrap profile applies the mounts, so the
754
817
  // command must NOT be wrapped a second time: the per-command probe still
@@ -835,7 +898,7 @@ export class WslShellExecutor extends LocalBashExecutor {
835
898
  // warning names the directory — the failure path pays the extra spawn,
836
899
  // the hot path does not.
837
900
  if (error instanceof SpawnError) {
838
- return this.executeOneShot(resolved, distro, shell, writableRoots).then((fallback) => fallback.result());
901
+ return this.executeOneShot(resolved, distro, shell, writableRoots, socketMasks, maskInterop).then((fallback) => fallback.result());
839
902
  }
840
903
  throw error;
841
904
  });
@@ -854,7 +917,7 @@ export class WslShellExecutor extends LocalBashExecutor {
854
917
  * @param shell - the resolved distro shell.
855
918
  * @returns the decorated execution result.
856
919
  */
857
- async executeOneShot(resolved, distro, shell, writableRoots = []) {
920
+ async executeOneShot(resolved, distro, shell, writableRoots = [], socketMasks = [], maskInterop = false) {
858
921
  const policy = resolved.sandboxPolicy;
859
922
  if (this.sandbox === undefined || policy === undefined || policy.mode === "danger-full-access") {
860
923
  // `executeArgv` resolves to the execution handle, so it has to be awaited
@@ -879,7 +942,7 @@ export class WslShellExecutor extends LocalBashExecutor {
879
942
  // closures.
880
943
  const mode = policy.mode;
881
944
  const confinement = { profile: undefined };
882
- const execution = await this.executeArgv(resolved, (signal) => this.prepareConfinedArgv(resolved, distro, shell, policy, mode, confinement, writableRoots, signal), (process) => this.stampConfinedFacts(resolved, mode, confinement, process));
945
+ const execution = await this.executeArgv(resolved, (signal) => this.prepareConfinedArgv(resolved, distro, shell, policy, mode, confinement, writableRoots, socketMasks, maskInterop, signal), (process) => this.stampConfinedFacts(resolved, mode, confinement, process));
883
946
  return WslShellExecutor.decorateResult(execution, (result) => {
884
947
  return this.settleConfinedOneShot(result, distro, resolved, mode, confinement.profile);
885
948
  }, (error) => {
@@ -905,13 +968,13 @@ export class WslShellExecutor extends LocalBashExecutor {
905
968
  * @param writableRoots - the effective extra roots the profile binds.
906
969
  * @param signal - the caller's cancellation.
907
970
  */
908
- async prepareConfinedArgv(resolved, distro, shell, policy, mode, slot, writableRoots, signal) {
971
+ async prepareConfinedArgv(resolved, distro, shell, policy, mode, slot, writableRoots, socketMasks, maskInterop, signal) {
909
972
  // Preparation is async, so it runs under executeArgv's deadline and
910
973
  // cancellation handling rather than before them. A distro without a
911
974
  // usable runner throws here, before anything is spawned. The outer
912
975
  // guard narrowed the sandbox in, but narrowings do not reach closures —
913
976
  // so the confined sandbox is asserted here, type-level only.
914
- const profile = await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode }, { distro, signal, writableRoots });
977
+ const profile = await this.sandbox.confine(this.distroArgv(resolved, shell), { ...policy, mode }, { distro, signal, writableRoots, socketMasks, maskInterop });
915
978
  slot.profile = profile;
916
979
  signal.throwIfAborted();
917
980
  return this.argv(resolved, distro, shell, profile.argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-wsl-env",
3
- "version": "0.26.4",
3
+ "version": "0.27.0",
4
4
  "description": "在 WSL 的 Linux 实例中打开项目工作区,在对应 Linux 空间中进行命令执行、运行 shell 脚本和文件访问,以获得全套 Linux Shell 工具链收益,并通过 bubblewrap 对命令进行沙箱隔离",
5
5
  "keywords": [
6
6
  "deepseek-harness",
@@ -79,6 +79,10 @@
79
79
  },
80
80
  "./picker/locale/en.json": "./locale/picker/en.json",
81
81
  "./picker/locale/zh.json": "./locale/picker/zh.json",
82
+ "./plugin-update": {
83
+ "types": "./lib/plugin-update.d.ts",
84
+ "default": "./lib/plugin-update.js"
85
+ },
82
86
  "./preflight": {
83
87
  "types": "./lib/preflight.d.ts",
84
88
  "default": "./lib/preflight.js"
@@ -215,9 +219,9 @@
215
219
  "build": "node scripts/build.mjs",
216
220
  "lint:build": "node test/build-freshness.mjs",
217
221
  "test:browser": "node --test --test-timeout=120000 test/browser/e2e.test.mjs",
218
- "test:coverage": "node scripts/coverage-gate.mjs -- node --test --test-timeout=60000 --experimental-test-coverage --test-coverage-lines=85 --test-coverage-branches=84 --test-coverage-functions=70 --test-coverage-exclude='scripts/**' --test-coverage-exclude='test/**' test/agent-exec.test.mjs test/agent-fs-script.test.mjs test/agent-protocol.test.mjs test/agent.test.mjs test/fs-substrate.test.mjs test/fs.boot.test.mjs test/composition.test.mjs test/bundle-mount.test.mjs test/hot-swap.test.mjs test/takeover-report.test.mjs test/provider.test.mjs test/provider-takeover.test.mjs test/file-reference-wsl.test.mjs test/fsio-agent.test.mjs test/fsio-text.test.mjs test/git-exec.test.mjs test/git-route.test.mjs test/listing.test.mjs test/paths.test.mjs test/ports.test.mjs test/preset-choice.test.mjs test/auto-preset.test.mjs test/probe-cache.test.mjs test/writable-roots.test.mjs test/preflight.test.mjs test/sandbox.test.mjs test/search-exec.test.mjs test/search-route.test.mjs test/shell.test.mjs test/shell-env.test.mjs test/terminal-activity.test.mjs test/terminal.test.mjs test/watcher.test.mjs test/wsl.test.mjs test/fs-decisions.test.mjs test/session-scope.test.mjs test/session-runtime.test.mjs test/native-agent.test.mjs test/peers.test.mjs test/agent-shared.test.mjs test/distro-route.test.mjs test/fs-routing.test.mjs test/update-check.test.mjs test/doctor.test.mjs test/doctor-collector.test.mjs test/release-scripts.test.mjs test/profile-preset.test.mjs test/packaging.test.mjs test/peer-canary.test.mjs test/probe-runner.test.mjs test/cwd-prompt.test.mjs test/cwd-prompt-tool.test.mjs test/wsl-doctor-tool.test.mjs test/wsl-doctor-command.test.mjs test/status.test.mjs test/client-host.test.mjs test/messages.test.mjs test/locales-examples.test.mjs test/client.test.mjs test/open-in-app.test.mjs",
222
+ "test:coverage": "node scripts/coverage-gate.mjs -- node --test --test-timeout=60000 --experimental-test-coverage --test-coverage-lines=85 --test-coverage-branches=84 --test-coverage-functions=70 --test-coverage-exclude='scripts/**' --test-coverage-exclude='test/**' test/agent-exec.test.mjs test/agent-fs-script.test.mjs test/agent-protocol.test.mjs test/agent.test.mjs test/fs-substrate.test.mjs test/fs.boot.test.mjs test/composition.test.mjs test/bundle-mount.test.mjs test/hot-swap.test.mjs test/takeover-report.test.mjs test/provider.test.mjs test/provider-takeover.test.mjs test/file-reference-wsl.test.mjs test/fsio-agent.test.mjs test/fsio-text.test.mjs test/git-exec.test.mjs test/git-route.test.mjs test/listing.test.mjs test/paths.test.mjs test/ports.test.mjs test/preset-choice.test.mjs test/auto-preset.test.mjs test/probe-cache.test.mjs test/writable-roots.test.mjs test/preflight.test.mjs test/sandbox.test.mjs test/socket-isolation.test.mjs test/search-exec.test.mjs test/search-route.test.mjs test/shell.test.mjs test/shell-env.test.mjs test/terminal-activity.test.mjs test/terminal.test.mjs test/watcher.test.mjs test/wsl.test.mjs test/fs-decisions.test.mjs test/session-scope.test.mjs test/session-runtime.test.mjs test/native-agent.test.mjs test/peers.test.mjs test/agent-shared.test.mjs test/distro-route.test.mjs test/fs-routing.test.mjs test/update-check.test.mjs test/plugin-update.test.mjs test/doctor.test.mjs test/doctor-collector.test.mjs test/release-scripts.test.mjs test/profile-preset.test.mjs test/packaging.test.mjs test/peer-canary.test.mjs test/probe-runner.test.mjs test/cwd-prompt.test.mjs test/cwd-prompt-tool.test.mjs test/wsl-doctor-tool.test.mjs test/wsl-doctor-command.test.mjs test/status.test.mjs test/client-host.test.mjs test/messages.test.mjs test/locales-examples.test.mjs test/client.test.mjs test/open-in-app.test.mjs",
219
223
  "test:syntax": "node test/syntax.mjs",
220
- "test:unit": "node scripts/test-watchdog.mjs -- node --test --test-timeout=60000 test/fs.boot.test.mjs test/fsio-text.test.mjs test/composition.test.mjs test/bundle-mount.test.mjs test/hot-swap.test.mjs test/takeover-report.test.mjs test/provider.test.mjs test/provider-takeover.test.mjs test/file-reference-wsl.test.mjs test/paths.test.mjs test/listing.test.mjs test/shell.test.mjs test/shell-env.test.mjs test/terminal.test.mjs test/probe-cache.test.mjs test/writable-roots.test.mjs test/preflight.test.mjs test/preset-choice.test.mjs test/auto-preset.test.mjs test/sandbox.test.mjs test/agent-protocol.test.mjs test/agent.test.mjs test/agent-fs-script.test.mjs test/fsio-agent.test.mjs test/fs-substrate.test.mjs test/agent-exec.test.mjs test/ports.test.mjs test/watcher.test.mjs test/wsl.test.mjs test/fs-decisions.test.mjs test/git-exec.test.mjs test/git-route.test.mjs test/search-route.test.mjs test/search-exec.test.mjs test/terminal-activity.test.mjs test/session-scope.test.mjs test/session-runtime.test.mjs test/native-agent.test.mjs test/peers.test.mjs test/agent-shared.test.mjs test/distro-route.test.mjs test/fs-routing.test.mjs test/update-check.test.mjs test/doctor.test.mjs test/doctor-collector.test.mjs test/release-scripts.test.mjs test/profile-preset.test.mjs test/packaging.test.mjs test/peer-canary.test.mjs test/probe-runner.test.mjs test/cwd-prompt.test.mjs test/cwd-prompt-tool.test.mjs test/wsl-doctor-tool.test.mjs test/wsl-doctor-command.test.mjs test/status.test.mjs test/client-host.test.mjs test/messages.test.mjs test/locales-examples.test.mjs test/client.test.mjs test/open-in-app.test.mjs",
224
+ "test:unit": "node scripts/test-watchdog.mjs -- node --test --test-timeout=60000 test/fs.boot.test.mjs test/fsio-text.test.mjs test/composition.test.mjs test/bundle-mount.test.mjs test/hot-swap.test.mjs test/takeover-report.test.mjs test/provider.test.mjs test/provider-takeover.test.mjs test/file-reference-wsl.test.mjs test/paths.test.mjs test/listing.test.mjs test/shell.test.mjs test/shell-env.test.mjs test/terminal.test.mjs test/probe-cache.test.mjs test/writable-roots.test.mjs test/preflight.test.mjs test/preset-choice.test.mjs test/auto-preset.test.mjs test/sandbox.test.mjs test/socket-isolation.test.mjs test/agent-protocol.test.mjs test/agent.test.mjs test/agent-fs-script.test.mjs test/fsio-agent.test.mjs test/fs-substrate.test.mjs test/agent-exec.test.mjs test/ports.test.mjs test/watcher.test.mjs test/wsl.test.mjs test/fs-decisions.test.mjs test/git-exec.test.mjs test/git-route.test.mjs test/search-route.test.mjs test/search-exec.test.mjs test/terminal-activity.test.mjs test/session-scope.test.mjs test/session-runtime.test.mjs test/native-agent.test.mjs test/peers.test.mjs test/agent-shared.test.mjs test/distro-route.test.mjs test/fs-routing.test.mjs test/update-check.test.mjs test/plugin-update.test.mjs test/doctor.test.mjs test/doctor-collector.test.mjs test/release-scripts.test.mjs test/profile-preset.test.mjs test/packaging.test.mjs test/peer-canary.test.mjs test/probe-runner.test.mjs test/cwd-prompt.test.mjs test/cwd-prompt-tool.test.mjs test/wsl-doctor-tool.test.mjs test/wsl-doctor-command.test.mjs test/status.test.mjs test/client-host.test.mjs test/messages.test.mjs test/locales-examples.test.mjs test/client.test.mjs test/open-in-app.test.mjs",
221
225
  "lint:style": "node test/style.mjs",
222
226
  "lint:links": "node scripts/check-links.mjs",
223
227
  "lint:requirements": "node scripts/check-requirements.mjs",
@@ -232,6 +236,7 @@
232
236
  "probe:sandbox-off": "bash test/probe/sandbox-off.sh",
233
237
  "probe:terminal": "bash test/probe/terminal.sh",
234
238
  "probe:sandbox": "bash test/probe/sandbox.sh",
239
+ "probe:cache-write": "bash test/probe/cache-write.sh",
235
240
  "probe:sandbox-shell": "bash test/probe/sandbox-shell.sh",
236
241
  "probe:interop-shell": "bash test/probe/interop-shell.sh",
237
242
  "sync:windows": "bash test/probe/sync-to-windows.sh",
@@ -72,6 +72,8 @@ import { fileURLToPath } from "node:url";
72
72
  import { parseDistroList } from "../lib/wsl.js";
73
73
  import { AGENT_NAME, PROTOCOL_VERSION, encodeExecFrame, encodeFsbFrame, parseAgentLine } from "../lib/agent-protocol.js";
74
74
  import { bwrapArgvPrefix } from "../lib/bwrap.js";
75
+ import { validateWritableRootsConfig, writableRootsCheckArgv } from "../lib/writable-roots.js";
76
+ import { parseSocketIsolationFacts, socketIsolationProbeScript, socketMaskPaths } from "../lib/socket-isolation.js";
75
77
  import { sessionScopeSweepScript } from "../lib/session-scope.js";
76
78
  import { parseListeningPorts, procNetScript } from "../lib/ports.js";
77
79
 
@@ -347,6 +349,9 @@ const QUICK_SECTIONS = ["host", "session", "sandbox"];
347
349
  * @property {string} sandbox - the fs-routing confinement stance.
348
350
  * @property {string} maskWindowsDrive - the drive-masking stance (when `interopVisibility` is unset).
349
351
  * @property {string} interopVisibility - the one-key stance (`""` unset, `visible`, `masked` or `disabled`); when set it takes precedence over `maskWindowsDrive`.
352
+ * @property {string[]} writableRoots - the `wsl-shell` row's extra `workspace-write` grants (the command plane).
353
+ * @property {string[]} writableRootsFs - the `wsl-fs` row's grants; the two rows must agree.
354
+ * @property {string} socketIsolation - the command/write rows' socket stance (`off`, `session-bus` or `strict`).
350
355
  * @property {string} source - where the values came from.
351
356
  * @property {string[]} overrides - the profile layers that changed keys, "`<name>`: `<keys>`".
352
357
  */
@@ -547,6 +552,48 @@ export function rowKey(block, key) {
547
552
  return (/** @type {RegExpExecArray} */ (match)[1] ?? "").trim().replace(/^['"]|['"]$/g, "");
548
553
  }
549
554
 
555
+ /**
556
+ * The list one key sets inside a row block, accepting the two YAML spellings
557
+ * the documentation uses: a flow list (`writableRoots: ['~/.npm', '~/.cache']`)
558
+ * or a block list (the key line, then indented `- value` lines). Anything else
559
+ * is a scalar and is returned as a one-item list, so a mistaken single value
560
+ * still reaches the validation rather than disappearing.
561
+ * @param {string} block - the row block's text.
562
+ * @param {string} key - the YAML key.
563
+ * @returns {string[] | undefined} the items (`[]` for an empty list), or undefined when unset.
564
+ */
565
+ export function rowList(block, key) {
566
+ const lines = block.split(/\r?\n/);
567
+ for (let index = 0; index < lines.length; index += 1) {
568
+ const match = new RegExp(`^(\\s*)${key}:\\s*(.*)$`).exec(/** @type {string} */ (lines[index]));
569
+ if (match === null) continue;
570
+ const indent = (match[1] ?? "").length;
571
+ const value = (match[2] ?? "").replace(/\s+#.*$/u, "").trim();
572
+ if (value.startsWith("[")) {
573
+ const inner = value.slice(1, value.endsWith("]") ? -1 : undefined);
574
+ /** @type {string[]} */
575
+ const items = [];
576
+ for (const item of inner.matchAll(/'([^']*)'|"([^"]*)"|([^,\s][^,]*)/gu)) {
577
+ const raw = (item[1] ?? item[2] ?? item[3] ?? "").trim();
578
+ if (raw.length > 0) items.push(raw.replace(/^['"]|['"]$/g, ""));
579
+ }
580
+ return items;
581
+ }
582
+ if (value.length > 0) return [value.replace(/^['"]|['"]$/g, "")];
583
+ /** @type {string[]} */
584
+ const items = [];
585
+ for (let next = index + 1; next < lines.length; next += 1) {
586
+ const line = /** @type {string} */ (lines[next]);
587
+ if (line.trim().length === 0 || line.trim().startsWith("#")) continue;
588
+ const item = /^(\s*)-\s+(.*)$/.exec(line);
589
+ if (item === null || (item[1] ?? "").length <= indent) break;
590
+ items.push((item[2] ?? "").trim().replace(/^['"]|['"]$/g, ""));
591
+ }
592
+ return items;
593
+ }
594
+ return undefined;
595
+ }
596
+
550
597
  /**
551
598
  * Read the configuration the blocking verdict must answer under: the shipped
552
599
  * preset's values, overlaid by every profile layer under `$DSH_HOME/profiles/*`
@@ -561,11 +608,13 @@ export function rowKey(block, key) {
561
608
  */
562
609
  export function effectiveConfig(dshHome, root) {
563
610
  /** @type {EffectiveConfig} */
564
- let config = { distro: "auto", sessionSandbox: "true", agentBackend: "auto", sandbox: "true", maskWindowsDrive: "false", interopVisibility: "", source: "the shipped preset", overrides: [] };
611
+ let config = { distro: "auto", sessionSandbox: "true", agentBackend: "auto", sandbox: "true", maskWindowsDrive: "false", interopVisibility: "", writableRoots: [], writableRootsFs: [], socketIsolation: "off", source: "the shipped preset", overrides: [] };
565
612
  let recognized = false;
566
613
  const shipped = readFileSync(join(root, "cordis.patch.yml"), "utf8");
567
614
  const preset = rowBlock(shipped, "preset-wsl");
568
615
  const routing = rowBlock(shipped, "fs-routing");
616
+ config.writableRoots = rowList(rowBlock(preset, "wsl-shell"), "writableRoots") ?? [];
617
+ config.writableRootsFs = rowList(rowBlock(preset, "wsl-fs"), "writableRoots") ?? [];
569
618
  const distro = rowKey(preset, "distro");
570
619
  const sessionSandbox = rowKey(preset, "sessionSandbox");
571
620
  const agentBackend = rowKey(preset, "agentBackend");
@@ -587,6 +636,9 @@ export function effectiveConfig(dshHome, root) {
587
636
  sandbox: sandbox ?? "true",
588
637
  maskWindowsDrive: maskWindowsDrive ?? "false",
589
638
  interopVisibility: rowKey(routing, "interopVisibility") ?? "",
639
+ writableRoots: config.writableRoots,
640
+ writableRootsFs: config.writableRootsFs,
641
+ socketIsolation: rowKey(preset, "socketIsolation") ?? rowKey(routing, "socketIsolation") ?? "off",
590
642
  source: "the shipped preset",
591
643
  overrides: [],
592
644
  };
@@ -603,10 +655,20 @@ export function effectiveConfig(dshHome, root) {
603
655
  const next = { ...config };
604
656
  const layerPreset = rowBlock(text, "preset-wsl");
605
657
  const layerRouting = rowBlock(text, "fs-routing");
606
- for (const [block, keys] of [[layerPreset, ["distro", "sessionSandbox", "agentBackend", "sandbox"]], [layerRouting, ["sandbox", "maskWindowsDrive"]]]) {
658
+ const layerShellRoots = rowList(rowBlock(layerPreset, "wsl-shell"), "writableRoots");
659
+ const layerFsRoots = rowList(rowBlock(layerPreset, "wsl-fs"), "writableRoots");
660
+ if (layerShellRoots !== undefined && JSON.stringify(layerShellRoots) !== JSON.stringify(next.writableRoots)) {
661
+ next.writableRoots = layerShellRoots;
662
+ changed.push("writableRoots");
663
+ }
664
+ if (layerFsRoots !== undefined && JSON.stringify(layerFsRoots) !== JSON.stringify(next.writableRootsFs)) {
665
+ next.writableRootsFs = layerFsRoots;
666
+ changed.push("writableRoots (wsl-fs)");
667
+ }
668
+ for (const [block, keys] of [[layerPreset, ["distro", "sessionSandbox", "agentBackend", "sandbox", "socketIsolation"]], [layerRouting, ["sandbox", "maskWindowsDrive", "socketIsolation"]]]) {
607
669
  const source = /** @type {string} */ (block);
608
670
  /** The scalar keys the overlay may change; `source`/`overrides` are bookkeeping, not overlay inputs. */
609
- const scalar = /** @type {const} */ (["distro", "sessionSandbox", "agentBackend", "sandbox", "maskWindowsDrive", "interopVisibility"]);
671
+ const scalar = /** @type {const} */ (["distro", "sessionSandbox", "agentBackend", "sandbox", "maskWindowsDrive", "interopVisibility", "socketIsolation"]);
610
672
  for (const key of /** @type {string[]} */ (keys)) {
611
673
  const value = rowKey(source, key);
612
674
  if (value === undefined || value === next[/** @type {keyof EffectiveConfig} */ (key)]) continue;
@@ -1334,6 +1396,140 @@ async function main(options) {
1334
1396
  }
1335
1397
  }
1336
1398
 
1399
+ // ---- writable roots ------------------------------------------------------
1400
+ // `workspace-write` grants the workspace and the temp areas; the toolchain
1401
+ // caches under `$HOME` need `writableRoots`. The bwrap rows above prove the
1402
+ // fence can run; this row names the extra roots the fence will bind and the
1403
+ // physical-path problems the runtime's one-time check refuses. It reads the
1404
+ // effective profile rows and runs one in-distro stat: it writes nothing and
1405
+ // creates no directory.
1406
+ if (!want("sandbox")) {
1407
+ // sandbox section out of scope
1408
+ } else if (sandboxDisabled) {
1409
+ check("sandbox.grants", "skipped", "Writable roots", "skipped: the sandbox is disabled; no extra roots are bound");
1410
+ } else {
1411
+ const shellRoots = effective.writableRoots;
1412
+ const fsRoots = effective.writableRootsFs;
1413
+ const mismatch = JSON.stringify([...shellRoots].sort()) !== JSON.stringify([...fsRoots].sort());
1414
+ /** @type {string[]} */
1415
+ const configured = [...new Set([...shellRoots, ...fsRoots])];
1416
+ /** Normalize one Linux path the way the runtime's resolver does.
1417
+ * @param {string} root - the raw path.
1418
+ * @returns {string} the absolute normalized path. */
1419
+ const normalize = (root) => {
1420
+ /** @type {string[]} */
1421
+ const parts = [];
1422
+ for (const part of root.split("/")) {
1423
+ if (part.length === 0 || part === ".") continue;
1424
+ if (part === "..") parts.pop();
1425
+ else parts.push(part);
1426
+ }
1427
+ return `/${parts.join("/")}`;
1428
+ };
1429
+ if (configured.length === 0) {
1430
+ check("sandbox.grants", "ok", "Writable roots", "none configured — workspace, /tmp and /dev/shm only; toolchain caches under $HOME need writableRoots");
1431
+ } else {
1432
+ /** @type {string | undefined} */
1433
+ let failure;
1434
+ /** @type {string | undefined} */
1435
+ let remedy;
1436
+ try {
1437
+ validateWritableRootsConfig(shellRoots);
1438
+ validateWritableRootsConfig(fsRoots);
1439
+ } catch (error) {
1440
+ failure = error instanceof Error ? error.message : String(error);
1441
+ remedy = "fix the writableRoots entry on both rows — an absolute Linux path or ~/...; see docs/CONFIGURATION.md#toolchain-caches-and-extra-writable-roots";
1442
+ }
1443
+ /** @type {string[]} */
1444
+ let roots = [];
1445
+ if (failure === undefined) {
1446
+ /** @type {string} */
1447
+ let home = "";
1448
+ if (configured.some((root) => root === "~" || root.startsWith("~/"))) {
1449
+ const homeAnswer = await probe('printf %s "$HOME"');
1450
+ if (homeAnswer.ok) home = homeAnswer.stdout.trim();
1451
+ if (home.length === 0 || !home.startsWith("/")) {
1452
+ failure = "the distro home did not answer, so ~ in writableRoots cannot be resolved";
1453
+ remedy = `run "wsl.exe -d ${target} --exec sh -c 'printf %s \\"$HOME\\"'" and retry`;
1454
+ }
1455
+ }
1456
+ if (failure === undefined) {
1457
+ roots = configured.map((root) => normalize(root === "~" ? home : root.startsWith("~/") ? `${home}/${root.slice(2)}` : root));
1458
+ const answer = await run(writableRootsCheckArgv(WSL, target, roots));
1459
+ if (!answer.ok) {
1460
+ const match = /(\d+)\|(missing|unreadable|symlink)(?: -> (.*))?/u.exec(`${answer.stdout}\n${answer.stderr}`);
1461
+ const index = match === null ? -1 : Number(match[1] ?? -1);
1462
+ const root = roots[index];
1463
+ if (root === undefined) {
1464
+ const first = answer.stderr.trim().split(/\r?\n/u)[0] ?? "";
1465
+ failure = `the writable-root check did not answer${first.length > 0 ? `: ${first.slice(0, 120)}` : ""}`;
1466
+ remedy = "rerun the doctor; if it persists, check that wsl.exe can run a command in the distro";
1467
+ } else {
1468
+ const reason = match?.[2];
1469
+ failure = reason === "missing"
1470
+ ? `${root} is missing`
1471
+ : reason === "unreadable"
1472
+ ? `${root} is unreadable`
1473
+ : `${root} is a symlink to ${match?.[3] ?? "another path"}`;
1474
+ remedy = reason === "missing"
1475
+ ? `create the directory inside "${target}" (mkdir -p ${root}) or remove it from writableRoots`
1476
+ : reason === "unreadable"
1477
+ ? `make ${root} readable and physically inside "${target}", or remove it from writableRoots`
1478
+ : `use the physical path ${match?.[3] ?? ""} in writableRoots; symlinked grants are not supported`;
1479
+ }
1480
+ }
1481
+ }
1482
+ }
1483
+ const listed = roots.length === configured.length ? roots : configured;
1484
+ const detail = mismatch
1485
+ ? `wsl-shell: ${shellRoots.length === 0 ? "(none)" : shellRoots.join(", ")}; wsl-fs: ${fsRoots.length === 0 ? "(none)" : fsRoots.join(", ")}`
1486
+ : `${listed.length} root(s): ${listed.join(", ")}`;
1487
+ if (failure !== undefined) {
1488
+ check("sandbox.grants", "warn", "Writable roots", `${detail} — ${failure}`, remedy);
1489
+ } else if (mismatch) {
1490
+ check("sandbox.grants", "warn", "Writable roots", `${detail} — the command and write rows bind different roots`, "put the same writableRoots list on wsl-shell and wsl-fs; see docs/CONFIGURATION.md#toolchain-caches-and-extra-writable-roots");
1491
+ } else {
1492
+ check("sandbox.grants", "ok", "Writable roots", `${detail} — all usable`);
1493
+ }
1494
+ }
1495
+ }
1496
+
1497
+ // ---- socket isolation ----------------------------------------------------
1498
+ // The mount profile does not govern process authority. This row names the
1499
+ // surface the command/write rows' socket stance covers and the escape
1500
+ // paths it leaves to the distro-level closure; the masks themselves are
1501
+ // verified by `pnpm run probe:sandbox`.
1502
+ if (!want("sandbox")) {
1503
+ // sandbox section out of scope
1504
+ } else if (sandboxDisabled) {
1505
+ check("sandbox.isolation", "skipped", "Socket isolation", "skipped: the sandbox is disabled; no socket masks are applied");
1506
+ } else {
1507
+ const stance = effective.socketIsolation;
1508
+ const answer = await probe(socketIsolationProbeScript());
1509
+ if (!answer.ok && answer.flaked) {
1510
+ flakeCheck("sandbox.isolation", "Socket isolation", answer);
1511
+ } else if (!answer.ok) {
1512
+ check("sandbox.isolation", "unknown", "Socket isolation", "the socket-facts probe did not answer", "rerun the doctor; if it persists, check that wsl.exe can run a command in the distro");
1513
+ } else {
1514
+ const valid = stance === "off" || stance === "session-bus" || stance === "strict";
1515
+ if (!valid) {
1516
+ check("sandbox.isolation", "warn", "Socket isolation", `unknown stance ${JSON.stringify(stance)} in the effective configuration`, "use off, session-bus or strict on the confined rows");
1517
+ } else {
1518
+ const facts = parseSocketIsolationFacts(answer.stdout);
1519
+ const masks = socketMaskPaths(stance, facts);
1520
+ const detected = [...facts.userSockets, ...facts.strictSockets];
1521
+ const surfaceText = detected.length === 0 ? "no matching socket detected" : detected.join(", ");
1522
+ if (stance === "off") {
1523
+ check("sandbox.isolation", "info", "Socket isolation", `off — confined commands can reach the user manager, system bus, container sockets and the interop transport; detected: ${surfaceText}`, "set socketIsolation: session-bus or strict on the confined rows (and fs-routing) to mask the sockets");
1524
+ } else if (stance === "session-bus") {
1525
+ check("sandbox.isolation", "ok", "Socket isolation", `session-bus — masks ${masks.length === 0 ? "no user-manager socket (none detected)" : masks.join(", ")}; the system bus, container sockets and the interop transport remain; enforcement stays partial`, "use strict to mask the system bus and reachable container sockets; close interop at the distro level");
1526
+ } else {
1527
+ check("sandbox.isolation", "ok", "Socket isolation", `strict — masks ${masks.length === 0 ? "no socket (none detected)" : masks.join(", ")}; the WSL interop transport is masked by the profile; same-user /proc remains; enforcement stays partial`, "the distro-level [interop] enabled=false still closes interop for the rest of the distro; same-user /proc is outside the mount profile");
1528
+ }
1529
+ }
1530
+ }
1531
+ }
1532
+
1337
1533
  // ---- session sandbox prerequisites --------------------------------------
1338
1534
  // The statuses are config-aware: the scope is only *required* under
1339
1535
  // `sessionSandbox: true` (the shipped default); `auto` falls back to the
@@ -111,7 +111,7 @@ function setKey(lines, id, key, value) {
111
111
  /**
112
112
  * Apply the supported edits to a preset block.
113
113
  * @param {string} block - the block from {@link presetBlock}.
114
- * @param {{ distro?: string, sessionSandbox?: boolean | "auto", sandbox?: boolean, maskWindowsDrive?: boolean, agentBackend?: string, writableRoots?: string[] }} edits - the edits.
114
+ * @param {{ distro?: string, sessionSandbox?: boolean | "auto", sandbox?: boolean, maskWindowsDrive?: boolean, agentBackend?: string, writableRoots?: string[], socketIsolation?: "off" | "session-bus" | "strict" }} edits - the edits.
115
115
  * @returns {string} the edited block.
116
116
  */
117
117
  export function applyEdits(block, edits) {
@@ -121,6 +121,7 @@ export function applyEdits(block, edits) {
121
121
  ["sessionSandbox", edits.sessionSandbox === undefined ? undefined : String(edits.sessionSandbox)],
122
122
  ["sandbox", edits.sandbox === undefined ? undefined : String(edits.sandbox)],
123
123
  ["maskWindowsDrive", edits.maskWindowsDrive === undefined ? undefined : String(edits.maskWindowsDrive)],
124
+ ["socketIsolation", edits.socketIsolation],
124
125
  ]);
125
126
  for (const [key, value] of both) {
126
127
  if (value === undefined) continue;
@@ -161,6 +162,13 @@ function parseArgs(argv) {
161
162
  else if (flag === "--agent-backend") {
162
163
  if (!["auto", "native", "shell"].includes(value)) throw new Error(`profile-preset: --agent-backend must be auto, native or shell (got "${value}")`);
163
164
  edits.agentBackend = value;
165
+ } else if (flag === "--socket-isolation") {
166
+ if (!["off", "session-bus", "strict"].includes(value)) throw new Error(`profile-preset: --socket-isolation must be off, session-bus or strict (got "${value}")`);
167
+ edits.socketIsolation = value;
168
+ } else if (flag === "--strict") {
169
+ edits.socketIsolation = "strict";
170
+ edits.maskWindowsDrive = true;
171
+ i -= 1;
164
172
  } else if (flag === "--writable-roots") {
165
173
  const roots = value.split(",").map((root) => root.trim()).filter((root) => root.length > 0);
166
174
  if (roots.length === 0) throw new Error("profile-preset: --writable-roots needs a comma-separated list of distro paths");
@@ -171,7 +179,7 @@ function parseArgs(argv) {
171
179
  options.force = true;
172
180
  i -= 1;
173
181
  } else if (flag === "--help" || flag === "-h") {
174
- console.log("node scripts/profile-preset.mjs [--distro NAME] [--session-sandbox true|false|auto] [--sandbox true|false] [--mask-windows-drive true|false] [--agent-backend auto|native|shell] [--writable-roots 'PATH,...'] [--out FILE] [--check FILE] [--force]");
182
+ console.log("node scripts/profile-preset.mjs [--distro NAME] [--session-sandbox true|false|auto] [--sandbox true|false] [--mask-windows-drive true|false] [--socket-isolation off|session-bus|strict] [--strict] [--agent-backend auto|native|shell] [--writable-roots 'PATH,...'] [--out FILE] [--check FILE] [--force]");
175
183
  process.exit(0);
176
184
  } else throw new Error(`profile-preset: unknown option "${arg}"`);
177
185
  }