@linxin666/dsh-win-bash 0.4.13 → 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/src/index.ts CHANGED
@@ -13,6 +13,18 @@
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 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
+ * import of this package fail with ERR_PNPM_EPERM. Publishing the payload
21
+ * outside the package is what lets an update or uninstall run while sessions
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.
27
+ *
16
28
  * Availability gate: win_bash serves sessions that run the LiangShen (梁神)
17
29
  * preset, so its registration follows that preset's DECLARATION in the
18
30
  * harness's agent-preset registry — declared means registered, undeclared
@@ -46,8 +58,8 @@ import type {} from '@deepseek-ai/dsh-tools'
46
58
  import { Config, resolveConfig, type WinBashConfig, type WinBashConfigInput } from './config.ts'
47
59
  import { startLiangShenGate, LIANGSHEN_PRESET_ID, type GateOptions, type GateOutcome } from './gate.ts'
48
60
  import { installPwshReplacement } from './pwsh-replacement.ts'
49
- import { resolveRuntime, type RuntimeReady, type HostPlatform } from './runtime.ts'
50
- import { ShellRegistry } from './shell.ts'
61
+ import { prepareRuntime, type RuntimeReady, type HostPlatform } from './runtime.ts'
62
+ import { ShellRegistry, sweepOrphanShellTempDirs } from './shell.ts'
51
63
  import { buildWinBashTool } from './tool.ts'
52
64
 
53
65
  export { BACKGROUND_JOB_KIND, startBackgroundJob } from './background.ts'
@@ -82,11 +94,16 @@ export {
82
94
  export { WIN_BASH_TOOL, renderResult, readJobRegistry, stripTerminalEscapes, truncationNotice } from './tool.ts'
83
95
  export type { RenderFacts } from './tool.ts'
84
96
  export {
97
+ SHELL_TEMP_PREFIX,
85
98
  ShellRegistry,
86
99
  ShellUnavailableError,
100
+ removeShellTempDir,
87
101
  shellArgv,
88
102
  shellEnvironment,
89
103
  shellTempDir,
104
+ sweepOrphanShellTempDirs,
105
+ type ShellTempSweep,
106
+ type ShellTempSweepOptions,
90
107
  } from './shell.ts'
91
108
  export { buildFrame, markerFor, parseFrame } from './protocol.ts'
92
109
  export {
@@ -107,12 +124,26 @@ export {
107
124
  type SettleStatus,
108
125
  } from './gate.ts'
109
126
  export {
127
+ CACHE_DIR_PARTS,
128
+ CACHE_STAGING_PREFIX,
129
+ ISOLATED_CACHE_DIR_PARTS,
130
+ RUNTIME_ROOT_ENV,
131
+ bashIn,
110
132
  bashPath,
133
+ binIn,
134
+ cacheRoot,
135
+ isolatedCacheRoot,
111
136
  parseChecksums,
137
+ payloadKey,
138
+ prepareRuntime,
112
139
  resolveRuntime,
113
140
  runtimeRoot,
141
+ shIn,
114
142
  shPath,
115
143
  verifyPayload,
144
+ verifyPayloadRoot,
145
+ type CopyTree,
146
+ type PrepareRuntimeOptions,
116
147
  } from './runtime.ts'
117
148
 
118
149
  /** Cordis plugin name; also the loader row id this package mounts under. */
@@ -254,7 +285,14 @@ export async function mountWithGate(
254
285
  */
255
286
  export function apply(ctx: Context, config?: WinBashConfigInput): void {
256
287
  const host: HostPlatform = { platform: process.platform, arch: process.arch }
257
- const runtime = resolveRuntime(host)
288
+ // The payload is published outside the package before the tool is built: a
289
+ // shell spawned from node_modules would make every later update or uninstall
290
+ // of this package fail with ERR_PNPM_EPERM while it runs. A cache that cannot
291
+ // be written keeps the tool working from the packaged tree and says so.
292
+ const runtime = prepareRuntime({
293
+ host,
294
+ warn: (message: string) => { ctx.logger?.warn?.('dsh-win-bash: ' + message) },
295
+ })
258
296
  if ('code' in runtime) {
259
297
  // Refusing the mount is the point: there is no fallback shell, and a
260
298
  // mounted tool that always errors is worse than an honest absence.
@@ -268,6 +306,27 @@ export function apply(ctx: Context, config?: WinBashConfigInput): void {
268
306
  ctx.logger?.error?.('dsh-win-bash: ' + (error instanceof Error ? error.message : String(error)))
269
307
  throw error
270
308
  }
309
+ // Every shell owns a private temp directory under the machine's temp root and
310
+ // deletes it when it stops. A crash or a hard kill ends this process first, and
311
+ // those directories are not small - whatever the commands wrote under TMP/TEMP
312
+ // is still in them. Their names carry the owning pid, so this start can tell
313
+ // which ones nobody owns any more; the sweep keeps the ones whose pid still
314
+ // runs. Detached like the mount continuation below, and self-contained, because
315
+ // an unreclaimed directory must never keep the plugin from mounting.
316
+ void sweepOrphanShellTempDirs().then((sweep) => {
317
+ if (sweep.removed.length > 0) {
318
+ ctx.logger?.info?.('dsh-win-bash: reclaimed ' + sweep.removed.length.toString()
319
+ + ' orphaned shell temp directories left by earlier runs')
320
+ }
321
+ if (sweep.failed.length > 0) {
322
+ ctx.logger?.warn?.('dsh-win-bash: ' + sweep.failed.length.toString()
323
+ + ' orphaned shell temp directories could not be reclaimed and will be retried on the next start: '
324
+ + sweep.failed.join(', '))
325
+ }
326
+ }, (error: unknown) => {
327
+ ctx.logger?.warn?.('dsh-win-bash: the orphaned shell temp directory sweep failed: '
328
+ + (error instanceof Error ? error.message : String(error)))
329
+ })
271
330
  // Deliberately detached (see mountWithGate), with a last-resort catch so no
272
331
  // defect above can surface as the unhandled rejection that kills the process.
273
332
  void mountWithGate(ctx, resolved, runtime).catch((error: unknown) => {
@@ -0,0 +1,161 @@
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
+
26
+ import { spawnSync } from 'node:child_process'
27
+ import { randomUUID } from 'node:crypto'
28
+ import { existsSync, mkdtempSync, readFileSync, rmdirSync, unlinkSync } from 'node:fs'
29
+ import { tmpdir } from 'node:os'
30
+ import { dirname, join, resolve } from 'node:path'
31
+
32
+ /** Integrity RID of Medium; a label below it downgrades a spawned process. */
33
+ export const MEDIUM_INTEGRITY_RID = 8192
34
+
35
+ /** Wall-clock bound on one icacls query for a security descriptor. */
36
+ export const READ_LABEL_TIMEOUT_MS = 5000
37
+
38
+ /** What one mandatory-integrity-label inspection established. */
39
+ export type IntegrityLabel = 'medium-or-higher' | 'low-or-untrusted' | 'unknown'
40
+
41
+ /**
42
+ * A reader for one path's mandatory integrity label. The seam exists so tests
43
+ * can drive Low/Unknown verdicts without touching the host's ACLs.
44
+ */
45
+ export type LabelReader = (target: string) => IntegrityLabel
46
+
47
+ /** One mandatory-label ACE inside an SDDL SACL: (ML;flags;rights;;;SID). */
48
+ const MANDATORY_LABEL_ACE = /\(ML;[^)]*;([^;)]+)\)/gi
49
+
50
+ /**
51
+ * Classify the mandatory label ACEs of one icacls /save SDDL blob.
52
+ *
53
+ * A missing SACL means the object has no explicit label and inherits Medium by
54
+ * default. High/System/Medium labels are harmless here; only Low or Untrusted
55
+ * can turn a Medium runner's child into a Low process.
56
+ * @param sddl - the UTF-16LE-decoded contents of an icacls /save file.
57
+ * @returns the label verdict. `unknown` is reserved for the reader that could
58
+ * not obtain or trust a descriptor at all; a parsed blob always decides.
59
+ */
60
+ export function parseIntegritySddl(sddl: string): IntegrityLabel {
61
+ // ML (SYSTEM_MANDATORY_LABEL_ACE_TYPE) only ever appears in the SACL. Taking
62
+ // everything after the S: marker keeps control flags such as AI/P/AR out of
63
+ // the match while still scanning every ACE in that section.
64
+ const sacl = /S:([^\r\n]*)/.exec(sddl)?.[1] ?? ''
65
+ for (const match of sacl.matchAll(MANDATORY_LABEL_ACE)) {
66
+ const sid = (match[1] ?? '').trim().toUpperCase()
67
+ if (sid === 'LW') return 'low-or-untrusted'
68
+ const numeric = /^S-1-16-(\d+)$/.exec(sid)
69
+ if (numeric !== null && Number(numeric[1]) < MEDIUM_INTEGRITY_RID) return 'low-or-untrusted'
70
+ }
71
+ return 'medium-or-higher'
72
+ }
73
+
74
+ /** Absolute path of the Windows icacls binary, never resolved through PATH. */
75
+ function icaclsPath(env: NodeJS.ProcessEnv): string {
76
+ return join(env.SystemRoot ?? env.windir ?? 'C:\\Windows', 'System32', 'icacls.exe')
77
+ }
78
+
79
+ /**
80
+ * Read one existing path's mandatory integrity label.
81
+ *
82
+ * On a POSIX host there is no Windows mandatory integrity control (and this
83
+ * package does not mount there), so the label cannot downgrade anything. A
84
+ * missing icacls, a failed query or an unreadable descriptor is reported as
85
+ * `unknown` rather than guessed: the caller decides whether to fall back.
86
+ * @param target - an existing file or directory to inspect.
87
+ * @param env - environment supplying SystemRoot; the live one by default.
88
+ * @returns the label verdict.
89
+ */
90
+ export function readMandatoryLabel(target: string, env: NodeJS.ProcessEnv = process.env): IntegrityLabel {
91
+ if (process.platform !== 'win32') return 'medium-or-higher'
92
+ const exe = icaclsPath(env)
93
+ if (!existsSync(exe)) return 'unknown'
94
+ let scratch: string | undefined
95
+ let aclFile: string | undefined
96
+ try {
97
+ scratch = mkdtempSync(join(tmpdir(), 'dsh-win-bash-acl-'))
98
+ aclFile = join(scratch, 'acl-' + randomUUID().slice(0, 8) + '.txt')
99
+ const run = spawnSync(exe, [target, '/save', aclFile], {
100
+ windowsHide: true,
101
+ timeout: READ_LABEL_TIMEOUT_MS,
102
+ stdio: 'ignore',
103
+ })
104
+ if (run.error !== undefined || run.status !== 0 || !existsSync(aclFile)) return 'unknown'
105
+ return parseIntegritySddl(readFileSync(aclFile).toString('utf16le'))
106
+ } catch {
107
+ return 'unknown'
108
+ } finally {
109
+ // Delete the two specific paths this call created; never a recursive delete.
110
+ if (aclFile !== undefined) {
111
+ try { unlinkSync(aclFile) } catch { /* already gone */ }
112
+ }
113
+ if (scratch !== undefined) {
114
+ try { rmdirSync(scratch) } catch { /* already gone */ }
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * The nearest existing path at or above `path`.
121
+ *
122
+ * A directory that does not exist yet has no descriptor of its own; a new file
123
+ * created below it inherits the label of the closest existing ancestor. That
124
+ * ancestor is what a pre-publication check has to inspect.
125
+ * @param path - the prospective path.
126
+ * @returns itself when it exists, otherwise its closest existing ancestor.
127
+ */
128
+ export function nearestExistingAncestor(path: string): string {
129
+ let current = resolve(path)
130
+ for (;;) {
131
+ if (existsSync(current)) return current
132
+ const parent = dirname(current)
133
+ if (parent === current) return current
134
+ current = parent
135
+ }
136
+ }
137
+
138
+ /** Bound on the directory chain walked, so a pathological path cannot spin. */
139
+ export const MAX_ANCESTOR_DEPTH = 32
140
+
141
+ /**
142
+ * Every existing path from `path` up to the volume root.
143
+ *
144
+ * A cache root can sit several levels below the data tree that a workspace
145
+ * sandbox labelled Low, and an inheritable ACE on ANY of those ancestors can
146
+ * still be propagated onto existing children later. Checking only the nearest
147
+ * existing ancestor would miss that, so the whole chain is inspected.
148
+ * @param path - the prospective path (it need not exist yet).
149
+ * @returns the existing ancestors, nearest first.
150
+ */
151
+ export function existingAncestors(path: string): string[] {
152
+ const found: string[] = []
153
+ let current = resolve(path)
154
+ for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth += 1) {
155
+ if (existsSync(current)) found.push(current)
156
+ const parent = dirname(current)
157
+ if (parent === current) break
158
+ current = parent
159
+ }
160
+ return found
161
+ }