@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/runtime.ts CHANGED
@@ -5,12 +5,33 @@
5
5
  * The package ships its own Git for Windows MinGit extraction under
6
6
  * runtime/win32-x64/: the tool must NEVER fall back to a bash found on PATH
7
7
  * (a host Git for Windows install, WSL, or a stray MSYS), because the whole
8
- * point of vendoring is a shell whose version and bytes are pinned. Two
8
+ * point of vendoring is a shell whose version and bytes are pinned. Four
9
9
  * invariants implement that:
10
10
  *
11
- * 1. the binary is addressed by absolute path inside the package, and
11
+ * 1. the binary is addressed by absolute path, never by name,
12
12
  * 2. every vendored byte is checked against the SHA256 manifest generated at
13
- * packaging time before the tool is mounted at all.
13
+ * packaging time before it is used at all, and
14
+ * 3. the tree that RUNS is a published copy under the DSH home, not the tree
15
+ * inside the package.
16
+ * 4. the copy's Windows mandatory integrity label is checked before it is
17
+ * reused or before a freshly published copy is spawned. A Low (or lower)
18
+ * label on the executable image makes Windows start a Low-integrity process
19
+ * even from a Medium runner, and that process cannot write an ordinary
20
+ * Medium workspace or temp directory. Such a tree is never used: the payload
21
+ * is published into an isolated cache root instead, and if no candidate root
22
+ * is safe the mount is refused with a specific diagnosis.
23
+ *
24
+ * The third invariant is why this module publishes a cache: Windows refuses to
25
+ * rename a directory whose executable is running, and pnpm imports a package by
26
+ * renaming a staging directory over it, so a shell spawned from inside
27
+ * node_modules makes every later update or uninstall of this package fail with
28
+ * ERR_PNPM_EPERM until the host stops. A persistent shell is this package's
29
+ * whole point, so the payload moves out of the package instead of the process
30
+ * moving out of the payload. The copy is content-addressed by the shipped
31
+ * manifest: the directory name is a digest of the payload's file identities, so
32
+ * a release that changes only JavaScript reuses the copy already published, and
33
+ * a copy whose bytes or manifest disagree with the shipped identity is never
34
+ * used.
14
35
  *
15
36
  * A mismatch refuses the mount with a specific message. The alternative —
16
37
  * mounting and hoping — would let a tampered or half-installed payload run
@@ -19,10 +40,16 @@
19
40
  * @module @linxin666/dsh-win-bash/runtime
20
41
  */
21
42
 
22
- import { createHash } from 'node:crypto'
23
- import { readFileSync, statSync } from 'node:fs'
43
+ import { createHash, randomUUID } from 'node:crypto'
44
+ import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
45
+ import { homedir } from 'node:os'
24
46
  import { dirname, join, resolve } from 'node:path'
25
47
  import { fileURLToPath } from 'node:url'
48
+ import { resolveDshHome } from './dsh-home.ts'
49
+ import {
50
+ existingAncestors, readMandatoryLabel,
51
+ type IntegrityLabel, type LabelReader,
52
+ } from './integrity.ts'
26
53
 
27
54
  /** Directory holding the shipped payload, relative to the package root. */
28
55
  export const RUNTIME_DIR = 'runtime/win32-x64'
@@ -36,27 +63,112 @@ export const RUNTIME_PLATFORM = 'win32'
36
63
  /** The one architecture this payload supports. */
37
64
  export const RUNTIME_ARCH = 'x64'
38
65
 
66
+ /**
67
+ * Payload cache directories under the DSH home, in order.
68
+ *
69
+ * The cache lives OUTSIDE the package on purpose: a running shell holds its own
70
+ * executable open, Windows refuses to rename a directory that holds a running
71
+ * executable, and pnpm imports a package by renaming over it. A copy here is
72
+ * also why a release that only changes JavaScript never has to move 16 MiB.
73
+ */
74
+ export const CACHE_DIR_PARTS = ['win-bash', 'runtime'] as const
75
+
76
+ /**
77
+ * Directory parts of the isolated fallback cache, used only when the preferred
78
+ * cache root carries a Low mandatory integrity label. It lives outside the DSH
79
+ * data tree, which a workspace sandbox can label Low with an inheritable ACE.
80
+ */
81
+ export const ISOLATED_CACHE_DIR_PARTS = ['dsh-win-bash', 'runtime'] as const
82
+
83
+ /**
84
+ * Optional environment override for the isolated cache root's parent. An
85
+ * operator whose local app data is itself labelled Low can point this at a
86
+ * directory they have verified is Medium; it is not needed on a normal host.
87
+ */
88
+ export const RUNTIME_ROOT_ENV = 'DSH_WIN_BASH_RUNTIME_HOME'
89
+
90
+ /**
91
+ * Name prefix of the staging directory one cache copy is built in. The rest of
92
+ * the name is the payload key, this process's id and a random suffix, so a
93
+ * half-written directory is never mistaken for a published payload.
94
+ */
95
+ export const CACHE_STAGING_PREFIX = '.staging-'
96
+
39
97
  /** Absolute package root (the directory holding package.json). */
40
98
  export const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
41
99
 
42
- /** Absolute payload root. */
100
+ /** Absolute payload root inside one package root. */
43
101
  export function runtimeRoot(packageRoot: string = PACKAGE_ROOT): string {
44
102
  return join(packageRoot, RUNTIME_DIR)
45
103
  }
46
104
 
47
- /** Absolute path of the vendored shell. */
105
+ /** Absolute path of the vendored shell inside one payload root. */
106
+ export function bashIn(root: string): string {
107
+ return join(root, 'usr', 'bin', 'bash.exe')
108
+ }
109
+
110
+ /** Absolute path of the vendored POSIX-shell alias inside one payload root. */
111
+ export function shIn(root: string): string {
112
+ return join(root, 'usr', 'bin', 'sh.exe')
113
+ }
114
+
115
+ /** Absolute path of one payload root's usr/bin directory. */
116
+ export function binIn(root: string): string {
117
+ return join(root, 'usr', 'bin')
118
+ }
119
+
120
+ /** Absolute path of the packaged payload's shell. */
48
121
  export function bashPath(packageRoot: string = PACKAGE_ROOT): string {
49
- return join(runtimeRoot(packageRoot), 'usr', 'bin', 'bash.exe')
122
+ return bashIn(runtimeRoot(packageRoot))
50
123
  }
51
124
 
52
- /** Absolute path of the vendored POSIX-shell alias of the same binary. */
125
+ /** Absolute path of the packaged payload's POSIX-shell alias. */
53
126
  export function shPath(packageRoot: string = PACKAGE_ROOT): string {
54
- return join(runtimeRoot(packageRoot), 'usr', 'bin', 'sh.exe')
127
+ return shIn(runtimeRoot(packageRoot))
55
128
  }
56
129
 
57
- /** Absolute path of the vendored payload's usr/bin directory. */
130
+ /** Absolute path of the packaged payload's usr/bin directory. */
58
131
  export function binDir(packageRoot: string = PACKAGE_ROOT): string {
59
- return join(runtimeRoot(packageRoot), 'usr', 'bin')
132
+ return binIn(runtimeRoot(packageRoot))
133
+ }
134
+
135
+ /**
136
+ * Absolute root of the per-user payload cache.
137
+ *
138
+ * It follows the DSH home rather than the package, so an isolated
139
+ * `DSH_HOME` (a probe instance, a test run) gets its own cache, and an update or
140
+ * uninstall of this package never touches a byte the cache holds.
141
+ * @param env - environment to read DSH_HOME from; the live one by default.
142
+ * @returns the directory payload copies are published under.
143
+ */
144
+ export function cacheRoot(env: NodeJS.ProcessEnv = process.env): string {
145
+ return join(resolveDshHome(env), ...CACHE_DIR_PARTS)
146
+ }
147
+
148
+ /**
149
+ * Absolute root of the isolated fallback payload cache.
150
+ *
151
+ * The DSH home is a data tree a workspace sandbox may have labelled Low with
152
+ * an inheritable ACE. A copy published below it then inherits that label and
153
+ * starts a Low-integrity bash, which cannot write a Medium workspace or temp
154
+ * directory. This root deliberately lives OUTSIDE the DSH home, under the
155
+ * per-user application-data (or cache) directory instead.
156
+ *
157
+ * It still follows the probe-isolation convention: the final path component is
158
+ * derived from the DSH home, so an isolated `DSH_HOME` gets its own isolated
159
+ * cache too. Operators whose application-data tree is itself labelled Low can
160
+ * point {@link RUNTIME_ROOT_ENV} at a directory they have verified.
161
+ * @param env - environment to read the override, app-data root and DSH home from.
162
+ * @returns the directory the fallback payload copies are published under.
163
+ */
164
+ export function isolatedCacheRoot(env: NodeJS.ProcessEnv = process.env): string {
165
+ const override = env[RUNTIME_ROOT_ENV]?.trim()
166
+ if (override !== undefined && override !== '') return resolve(override)
167
+ const base = env.LOCALAPPDATA
168
+ ?? (process.platform === 'win32'
169
+ ? join(homedir(), 'AppData', 'Local')
170
+ : (env.XDG_CACHE_HOME ?? join(homedir(), '.cache')))
171
+ return join(base, ...ISOLATED_CACHE_DIR_PARTS, sha256(resolveDshHome(env)).slice(0, 12))
60
172
  }
61
173
 
62
174
  /** One manifest row: a payload-relative path and its digest. */
@@ -110,6 +222,19 @@ export function sha256(bytes: Buffer | string): string {
110
222
  return createHash('sha256').update(bytes).digest('hex')
111
223
  }
112
224
 
225
+ /**
226
+ * The content key of one payload: a digest over its manifest's file identities.
227
+ *
228
+ * Manifest formatting and row order do not move it, and any change to a
229
+ * payload file does. That is what makes a cache directory name a statement
230
+ * about the bytes inside it rather than about the release that shipped them.
231
+ * @param entries - the parsed manifest rows.
232
+ * @returns the 16-character key that names the cache directory.
233
+ */
234
+ export function payloadKey(entries: readonly ChecksumEntry[]): string {
235
+ return sha256(entries.map(entry => entry.path + ' ' + entry.sha256).sort().join('\n')).slice(0, 16)
236
+ }
237
+
113
238
  /**
114
239
  * Verify every registered payload file against the shipped manifest.
115
240
  *
@@ -121,7 +246,20 @@ export function sha256(bytes: Buffer | string): string {
121
246
  * @throws when the manifest itself is unreadable or malformed.
122
247
  */
123
248
  export function verifyPayload(packageRoot: string = PACKAGE_ROOT): ChecksumReport {
124
- const root = runtimeRoot(packageRoot)
249
+ return verifyPayloadRoot(runtimeRoot(packageRoot))
250
+ }
251
+
252
+ /**
253
+ * Verify every payload file of one payload root against that root's manifest.
254
+ *
255
+ * The root is the directory holding `usr/` and `checksums.sha256`, which is
256
+ * either the packaged payload or a published cache copy, so both go through the
257
+ * same pass.
258
+ * @param root - the payload root to verify.
259
+ * @returns the count of verified files and every mismatch found.
260
+ * @throws when the manifest itself is unreadable or malformed.
261
+ */
262
+ export function verifyPayloadRoot(root: string): ChecksumReport {
125
263
  const manifest = parseChecksums(readFileSync(join(root, CHECKSUM_FILE), 'utf8'))
126
264
  const mismatches: ChecksumMismatch[] = []
127
265
  let verified = 0
@@ -151,16 +289,21 @@ export interface RuntimeRejection {
151
289
  | 'missing-binary'
152
290
  | 'checksum-mismatch'
153
291
  | 'manifest-unreadable'
292
+ | 'unsafe-integrity'
154
293
  /** One-sentence, operator-facing explanation. */
155
294
  readonly message: string
156
295
  }
157
296
 
158
297
  /** Successful payload resolution. */
159
298
  export interface RuntimeReady {
160
- /** Absolute path of the vendored bash.exe. */
299
+ /** Absolute path of the vendored bash.exe that will be spawned. */
161
300
  readonly bash: string
162
301
  /** Absolute path of the payload's usr/bin. */
163
302
  readonly bin: string
303
+ /** Absolute payload root both paths above live in. */
304
+ readonly payloadRoot: string
305
+ /** Whether that root is the published cache copy or the packaged tree. */
306
+ readonly source: 'cache' | 'package'
164
307
  }
165
308
 
166
309
  /** Whether the running host can serve this payload at all. */
@@ -172,19 +315,11 @@ export interface HostPlatform {
172
315
  }
173
316
 
174
317
  /**
175
- * Resolve the vendored shell for one host, or refuse the mount.
176
- *
177
- * The order is deliberate: platform, then architecture, then presence, then
178
- * integrity. A checksum failure names the first mismatching path so an
179
- * operator can act on it, and no path here ever consults PATH.
318
+ * Refuse a host that cannot run this payload at all.
180
319
  * @param host - the running host's platform facts.
181
- * @param packageRoot - package root holding the payload.
182
- * @returns the resolved shell paths, or the rejection reason.
320
+ * @returns the rejection, or undefined when the host could serve the payload.
183
321
  */
184
- export function resolveRuntime(
185
- host: HostPlatform,
186
- packageRoot: string = PACKAGE_ROOT,
187
- ): RuntimeReady | RuntimeRejection {
322
+ function rejectHost(host: HostPlatform): RuntimeRejection | undefined {
188
323
  if (host.platform !== RUNTIME_PLATFORM) {
189
324
  return {
190
325
  code: 'unsupported-platform',
@@ -200,6 +335,33 @@ export function resolveRuntime(
200
335
  message: 'win_bash currently ships only the ' + RUNTIME_ARCH + ' payload; this host is ' + host.arch + '.',
201
336
  }
202
337
  }
338
+ return undefined
339
+ }
340
+
341
+ /** The three paths one payload root provides, tagged with where it came from. */
342
+ function readyFrom(root: string, source: RuntimeReady['source']): RuntimeReady {
343
+ return { bash: bashIn(root), bin: binIn(root), payloadRoot: root, source }
344
+ }
345
+
346
+ /**
347
+ * Resolve the PACKAGED shell for one host, or refuse the mount.
348
+ *
349
+ * The order is deliberate: platform, then architecture, then presence, then
350
+ * integrity. A checksum failure names the first mismatching path so an
351
+ * operator can act on it, and no path here ever consults PATH.
352
+ *
353
+ * This is the packaged tree, not the cache: callers that intend to RUN the
354
+ * shell want {@link prepareRuntime}, which publishes a copy first.
355
+ * @param host - the running host's platform facts.
356
+ * @param packageRoot - package root holding the payload.
357
+ * @returns the resolved shell paths, or the rejection reason.
358
+ */
359
+ export function resolveRuntime(
360
+ host: HostPlatform,
361
+ packageRoot: string = PACKAGE_ROOT,
362
+ ): RuntimeReady | RuntimeRejection {
363
+ const refused = rejectHost(host)
364
+ if (refused !== undefined) return refused
203
365
  const bash = bashPath(packageRoot)
204
366
  try {
205
367
  if (!statSync(bash).isFile()) throw new Error('not a file')
@@ -236,5 +398,294 @@ export function resolveRuntime(
236
398
  + '). Reinstall the package; win_bash will not run an unverified payload.',
237
399
  }
238
400
  }
239
- return { bash, bin: binDir(packageRoot) }
401
+ return readyFrom(runtimeRoot(packageRoot), 'package')
402
+ }
403
+
404
+ /** One tree copy: the source payload root, the directory to fill. */
405
+ export type CopyTree = (source: string, target: string) => void
406
+
407
+ /** Where payload publication can be redirected, and what it reports. */
408
+ export interface PrepareRuntimeOptions {
409
+ /** The running host's platform facts; this process's by default. */
410
+ readonly host?: HostPlatform
411
+ /** Package root holding runtime/win32-x64; this package's own by default. */
412
+ readonly packageRoot?: string
413
+ /** Cache root to publish into; the DSH home's own by default. */
414
+ readonly cacheRoot?: string
415
+ /** Isolated fallback root; the per-user app-data cache by default. */
416
+ readonly isolatedCacheRoot?: string
417
+ /** Environment the default roots resolve from; process.env by default. */
418
+ readonly env?: NodeJS.ProcessEnv
419
+ /** Mandatory-integrity-label reader; the Windows icacls reader by default. */
420
+ readonly readLabel?: LabelReader
421
+ /** Operator-facing notes; a copy that could not be published is reported here. */
422
+ readonly warn?: (message: string) => void
423
+ /** The copy itself; a real recursive copy by default. */
424
+ readonly copy?: CopyTree
425
+ }
426
+
427
+ /** The recursive copy one published payload is built with. */
428
+ function copyTree(source: string, target: string): void {
429
+ cpSync(source, target, { recursive: true, force: true, preserveTimestamps: true })
430
+ }
431
+
432
+ /** One error's message, for an operator-facing line. */
433
+ function describe(error: unknown): string {
434
+ return error instanceof Error ? error.message : String(error)
435
+ }
436
+
437
+ /** Delete a staging directory, never letting a failed reclaim escape. */
438
+ function removeStaging(staging: string): void {
439
+ try {
440
+ rmSync(staging, { recursive: true, force: true })
441
+ } catch {
442
+ // An unreclaimed staging directory is inert: its name is not a payload key,
443
+ // so no mount can mistake it for a published copy.
444
+ }
445
+ }
446
+
447
+ /**
448
+ * Whether one directory is a complete copy of the payload the key names.
449
+ *
450
+ * The copy's own manifest must reproduce the expected key before any byte is
451
+ * executed, so a directory whose manifest was rewritten alongside its files is
452
+ * a miss rather than a match. This is a BYTE check only: it says nothing about
453
+ * the security descriptor, which is why callers also run {@link cacheSafe}.
454
+ * @param root - the candidate payload root.
455
+ * @param key - the key the shipped manifest produced.
456
+ * @returns whether that directory's bytes can be spawned from.
457
+ */
458
+ function cacheReady(root: string, key: string): boolean {
459
+ try {
460
+ if (payloadKey(parseChecksums(readFileSync(join(root, CHECKSUM_FILE), 'utf8'))) !== key) return false
461
+ if (!statSync(bashIn(root)).isFile()) return false
462
+ const report = verifyPayloadRoot(root)
463
+ return report.verified > 0 && report.mismatches.length === 0
464
+ } catch {
465
+ return false
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Whether a published tree's mandatory integrity label is safe to spawn from.
471
+ *
472
+ * Both the directory and the executable itself are inspected: the Windows
473
+ * sandbox applies an inheritable Low ACE to the directory, and the image then
474
+ * carries an inherited Low ACE. Before a directory exists, the closest existing
475
+ * ancestor is what decides the label a newly created file inherits.
476
+ *
477
+ * `unknown` is not treated as safe. A descriptor we cannot read cannot be
478
+ * claimed as verified, so the caller moves on to another candidate root rather
479
+ * than silently running from an unverified image.
480
+ * @param root - the candidate payload root.
481
+ * @param readLabel - the label reader (injectable seam).
482
+ * @returns the label verdict for that tree.
483
+ */
484
+ function cacheSafe(root: string, readLabel: LabelReader): IntegrityLabel {
485
+ // Every existing ancestor matters: an inheritable Low ACE on the DSH home
486
+ // can be propagated onto existing children after the cache was published.
487
+ const verdicts = existingAncestors(root).map(target => readLabel(target))
488
+ const bash = bashIn(root)
489
+ if (existsSync(bash)) verdicts.push(readLabel(bash))
490
+ if (verdicts.includes('low-or-untrusted')) return 'low-or-untrusted'
491
+ if (verdicts.includes('unknown')) return 'unknown'
492
+ return 'medium-or-higher'
493
+ }
494
+
495
+ /**
496
+ * Publish one payload copy under its key.
497
+ *
498
+ * The copy is built in a staging directory beside the target and renamed into
499
+ * place, so the published name only ever refers to a complete tree. A rename
500
+ * that loses a race against another host publishing the same key is not a
501
+ * failure: both hosts copy the same bytes by construction.
502
+ * @param source - the packaged payload root to copy.
503
+ * @param target - the cache directory the key names.
504
+ * @param key - the payload key, carried into the staging name.
505
+ * @param copy - the copy itself.
506
+ */
507
+ function publishPayload(source: string, target: string, key: string, copy: CopyTree): void {
508
+ mkdirSync(dirname(target), { recursive: true })
509
+ // A directory already sitting at the key has failed its verification (the
510
+ // caller only publishes on a miss), so it is unusable and has to go before a
511
+ // rename can land. A copy a live shell still holds open refuses the delete on
512
+ // Windows, and that refusal reaches the caller as an honest fallback.
513
+ if (existsSync(target)) rmSync(target, { recursive: true, force: true })
514
+ const staging = join(
515
+ dirname(target),
516
+ CACHE_STAGING_PREFIX + key + '-' + process.pid.toString() + '-' + randomUUID().slice(0, 8),
517
+ )
518
+ try {
519
+ copy(source, staging)
520
+ renameSync(staging, target)
521
+ } catch (error) {
522
+ removeStaging(staging)
523
+ if (cacheReady(target, key)) return
524
+ throw error
525
+ }
526
+ }
527
+
528
+ /**
529
+ * Why one candidate cache root could not serve the payload.
530
+ *
531
+ * A Low verdict is a security fact, not a write failure: the tree must not be
532
+ * reused or spawned from at all. The other reasons keep the existing honest
533
+ * fallback to the verified packaged tree.
534
+ */
535
+ interface CacheDiagnosis {
536
+ /** Operator-facing explanation. */
537
+ readonly message: string
538
+ /** Whether a Low/Untrusted mandatory label was actually observed. */
539
+ readonly low: boolean
540
+ }
541
+
542
+ /**
543
+ * Resolve the shell one host runs, publishing the payload outside the package.
544
+ *
545
+ * Two independent proofs gate every tree that can be spawned: the shipped
546
+ * SHA256 manifest proves its BYTES, and a mandatory-integrity-label check
547
+ * proves its SECURITY DESCRIPTOR cannot downgrade a Medium runner to a Low
548
+ * process. A label check runs before a published copy is reused, before a new
549
+ * copy is published, and again after publication (the decisive check is on the
550
+ * bash.exe that will actually be spawned). A tree carrying Low or Untrusted is
551
+ * never reused and never spawned from, so a hash match alone can no longer keep
552
+ * a broken cache alive across restarts and updates.
553
+ *
554
+ * Candidate roots are tried in order. The DSH home cache keeps the #1996 fix;
555
+ * when its data tree is labelled Low, the payload is published into an isolated
556
+ * per-user application-data root instead, still OUTSIDE the package. An old Low
557
+ * cache under the DSH home is therefore migrated by abandonment, not by a
558
+ * one-off repair of one payload-key directory.
559
+ *
560
+ * When no candidate can be written or verified, the verified packaged tree runs
561
+ * instead and the caller is told, through {@link PrepareRuntimeOptions.warn},
562
+ * that updates will need this host stopped. But if a Low label was observed and
563
+ * even the packaged image is not proven clean, the mount is REFUSED with
564
+ * `unsafe-integrity` rather than silently executing a shell that cannot write
565
+ * the session's workspace. A payload that fails its manifest is always a
566
+ * refusal, cache or no cache.
567
+ * @param options - host facts, roots, and the seams tests drive.
568
+ * @returns the shell paths to run, or the rejection reason.
569
+ */
570
+ export function prepareRuntime(options: PrepareRuntimeOptions = {}): RuntimeReady | RuntimeRejection {
571
+ const host = options.host ?? { platform: process.platform, arch: process.arch }
572
+ const refused = rejectHost(host)
573
+ if (refused !== undefined) return refused
574
+ const packageRoot = options.packageRoot ?? PACKAGE_ROOT
575
+ const source = runtimeRoot(packageRoot)
576
+ const warn = options.warn ?? ((): void => {})
577
+ // One mount inspects the same ancestors several times (before reuse, before
578
+ // publication, after publication). Memoize within this call: a descriptor
579
+ // cannot change underneath us, and icacls is a process per query.
580
+ const rawLabel = options.readLabel ?? readMandatoryLabel
581
+ const labels = new Map<string, IntegrityLabel>()
582
+ const readLabel: LabelReader = (target: string): IntegrityLabel => {
583
+ const hit = labels.get(target)
584
+ if (hit !== undefined) return hit
585
+ const verdict = rawLabel(target)
586
+ labels.set(target, verdict)
587
+ return verdict
588
+ }
589
+ const copy = options.copy ?? copyTree
590
+
591
+ // A caller that names cacheRoot explicitly (tests, probe instances) owns the
592
+ // candidate set: it must also name isolatedCacheRoot to get a second one.
593
+ // Only the real default path adds the isolated fallback automatically.
594
+ const roots = [options.cacheRoot ?? cacheRoot(options.env)]
595
+ const isolated = options.isolatedCacheRoot
596
+ ?? (options.cacheRoot === undefined ? isolatedCacheRoot(options.env) : undefined)
597
+ if (isolated !== undefined && !roots.includes(isolated)) roots.push(isolated)
598
+
599
+ let key: string
600
+ try {
601
+ key = payloadKey(parseChecksums(readFileSync(join(source, CHECKSUM_FILE), 'utf8')))
602
+ } catch (error) {
603
+ return {
604
+ code: 'manifest-unreadable',
605
+ message: 'the payload checksum manifest could not be read: ' + describe(error),
606
+ }
607
+ }
608
+
609
+ const diagnoses: CacheDiagnosis[] = []
610
+ let shipped: RuntimeReady | RuntimeRejection | undefined
611
+ const verifiedPackage = (): RuntimeReady | RuntimeRejection => {
612
+ shipped ??= resolveRuntime(host, packageRoot)
613
+ return shipped
614
+ }
615
+
616
+ for (const cacheDir of roots) {
617
+ const published = join(cacheDir, key)
618
+
619
+ // Before reuse AND before publication: never touch a Low-labelled tree.
620
+ const before = cacheSafe(published, readLabel)
621
+ if (before === 'low-or-untrusted') {
622
+ diagnoses.push({
623
+ low: true,
624
+ message: 'the cache root ' + cacheDir + ' carries a Low or Untrusted mandatory integrity label',
625
+ })
626
+ continue
627
+ }
628
+ if (before === 'unknown') {
629
+ diagnoses.push({
630
+ low: false,
631
+ message: 'the mandatory integrity label of ' + cacheDir + ' could not be read',
632
+ })
633
+ continue
634
+ }
635
+
636
+ if (cacheReady(published, key)) return readyFrom(published, 'cache')
637
+
638
+ const packaged = verifiedPackage()
639
+ if ('code' in packaged) return packaged
640
+ try {
641
+ publishPayload(source, published, key, copy)
642
+ } catch (error) {
643
+ diagnoses.push({
644
+ low: false,
645
+ message: 'the verified payload could not be published to ' + published + ' (' + describe(error) + ')',
646
+ })
647
+ continue
648
+ }
649
+ if (!cacheReady(published, key)) {
650
+ diagnoses.push({
651
+ low: false,
652
+ message: 'the payload copy at ' + published + ' did not verify against the shipped manifest',
653
+ })
654
+ continue
655
+ }
656
+
657
+ // After publication: the label a freshly created bash.exe INHERITED is the
658
+ // decisive fact. A tree that turned Low here is never returned to a caller.
659
+ const after = cacheSafe(published, readLabel)
660
+ if (after !== 'medium-or-higher') {
661
+ diagnoses.push({
662
+ low: after === 'low-or-untrusted',
663
+ message: after === 'low-or-untrusted'
664
+ ? 'the newly published bash.exe at ' + bashIn(published) + ' inherited a Low or Untrusted mandatory integrity label'
665
+ : 'the mandatory integrity label of the newly published bash.exe at ' + bashIn(published) + ' could not be read',
666
+ })
667
+ continue
668
+ }
669
+ return readyFrom(published, 'cache')
670
+ }
671
+
672
+ const packaged = verifiedPackage()
673
+ if ('code' in packaged) return packaged
674
+ const reasons = diagnoses.map(entry => entry.message).join('; ')
675
+ const sawLow = diagnoses.some(entry => entry.low)
676
+ const packagedLabel = readLabel(bashPath(packageRoot))
677
+ if (sawLow && packagedLabel === 'low-or-untrusted') {
678
+ return {
679
+ code: 'unsafe-integrity',
680
+ message: 'every runtime cache root is unsafe to spawn from and the packaged payload is not proven clean: '
681
+ + reasons + '. A Low-labelled bash.exe would start a Low-integrity process on this Medium host, which '
682
+ + 'cannot write an ordinary workspace or temp directory, so win_bash refuses to mount instead of '
683
+ + 'silently running a broken shell. Use the host pwsh tool, or point ' + RUNTIME_ROOT_ENV
684
+ + ' at a directory you have verified has no Low Mandatory Level label. Do not lower the '
685
+ + 'workspace integrity level or change the global sandbox policy to work around this.',
686
+ }
687
+ }
688
+ warn(reasons + ', so this host runs the shell from ' + source + '; while it runs, updating or '
689
+ + 'uninstalling this package can fail with ERR_PNPM_EPERM')
690
+ return packaged
240
691
  }