dsh-bash-terminal-ts 0.9.1 → 0.9.3

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 (71) hide show
  1. package/CHANGELOG.md +214 -205
  2. package/CHANGELOG.pt.md +151 -151
  3. package/README.de.md +206 -206
  4. package/README.en.md +212 -212
  5. package/README.es.md +206 -206
  6. package/README.fr.md +206 -206
  7. package/README.it.md +206 -206
  8. package/README.md +423 -423
  9. package/README.pt.md +212 -212
  10. package/README.ru.md +206 -206
  11. package/agent-presets/README.md +171 -171
  12. package/agent-presets/install-presets.mjs +180 -180
  13. package/agent-presets/standard-win/agent.cordis.yml +271 -271
  14. package/agent-presets/standard-win/preset.yml +2 -2
  15. package/agent-presets/standard-win-gitbash/agent.cordis.yml +271 -271
  16. package/agent-presets/standard-win-gitbash/preset.yml +2 -2
  17. package/agent-presets/standard-win-msys2/agent.cordis.yml +272 -272
  18. package/agent-presets/standard-win-msys2/preset.yml +2 -2
  19. package/agent-presets/standard-win-niu/agent.cordis.yml +270 -270
  20. package/agent-presets/standard-win-niu/preset.yml +2 -2
  21. package/agent-presets/standard-win-wsl2/agent.cordis.yml +271 -271
  22. package/agent-presets/standard-win-wsl2/preset.yml +2 -2
  23. package/cordis.patch.yml +72 -84
  24. package/dist/client.core.js +193 -12
  25. package/dist/client.js +193 -12
  26. package/docs/niu-backend.md +197 -197
  27. package/dsh.plugin.json +23 -23
  28. package/lib/client.js +193 -12
  29. package/lib/dsh-types.d.ts +0 -2
  30. package/lib/index.d.ts +2 -23
  31. package/lib/index.js +4 -34
  32. package/lib/locales.js +0 -10
  33. package/lib/shell-id.d.ts +2 -2
  34. package/lib/shells.d.ts +2 -11
  35. package/lib/shells.js +4 -14
  36. package/lib/terminal.js +0 -1
  37. package/lib/webterminals/catalog.d.ts +0 -2
  38. package/lib/webterminals/catalog.js +0 -1
  39. package/lib/webterminals/mount.d.ts +0 -5
  40. package/lib/webterminals/mount.js +0 -4
  41. package/locale/de.json +5 -5
  42. package/locale/en.json +5 -5
  43. package/locale/es.json +5 -5
  44. package/locale/fr.json +5 -5
  45. package/locale/it.json +5 -5
  46. package/locale/ja.json +5 -5
  47. package/locale/ko.json +5 -5
  48. package/locale/pt.json +6 -6
  49. package/locale/ru.json +5 -5
  50. package/locale/zh.json +5 -5
  51. package/package.json +1 -5
  52. package/scripts/check-artifacts.mjs +96 -96
  53. package/scripts/link-shells.mjs +0 -21
  54. package/src/client.tsx +687 -685
  55. package/src/dsh-types.ts +330 -332
  56. package/src/index.ts +1267 -1316
  57. package/src/locales.ts +499 -509
  58. package/src/shell-id.ts +11 -11
  59. package/src/shells.ts +263 -279
  60. package/src/terminal.ts +615 -616
  61. package/src/webterminals/browser/star-row-copy.ts +256 -0
  62. package/src/webterminals/catalog.ts +0 -3
  63. package/src/webterminals/host.ts +361 -361
  64. package/src/webterminals/mount.ts +228 -237
  65. package/agent-presets/standard-win-payload/agent.cordis.yml +0 -271
  66. package/agent-presets/standard-win-payload/preset.yml +0 -2
  67. package/lib/payload.d.ts +0 -72
  68. package/lib/payload.js +0 -279
  69. package/scripts/payload-alias.mjs +0 -97
  70. package/scripts/provision-payload.mjs +0 -233
  71. package/src/payload.ts +0 -322
@@ -1,97 +0,0 @@
1
- // scripts/payload-alias.mjs - the payload's entry in the HOST's right-sidebar
2
- // terminal menu, shared by link-shells.mjs and provision-payload.mjs.
3
- //
4
- // Why a hard link with its own name (same rule as git-bash.exe / msys-bash.exe):
5
- // `discoverShells` keys its Map by the executable FILE NAME and keeps the
6
- // earliest entry. The payload's binary is `bash.exe` - the same key the stock
7
- // list spends on `C:\Windows\System32\bash.exe`, the WSL forwarder. A link
8
- // inside the payload's own `bin\` named `bash-terminal.exe` (a) cannot collide
9
- // with the WSL `bash` row, (b) is only ever present after an operator
10
- // provisioned AND digest-verified a payload, and (c) keeps bash's POSIX-root
11
- // derivation intact because it sits next to the original in the same tree.
12
- //
13
- // Why a junction (`payloads\bash-terminal` -> `payloads\posix-<ver>`): the
14
- // bundle patch's candidate path must be a STABLE string - the version dir
15
- // changes with every re-provision, the junction does not. Directory junctions
16
- // need no privilege and may cross volumes, so the store layout is:
17
- //
18
- // %LOCALAPPDATA%\dsh-bash-terminal-ts\payloads\
19
- // posix-5.2.37(1)\ <- the verified root (provision writes here)
20
- // bin\bash.exe <- upstream binary
21
- // bin\bash-terminal.exe <- hard link, the menu's own name
22
- // bash-terminal\ (junction) <- stable path the patch points at
23
- //
24
- // The patch candidate is built with `!!js` from LOCALAPPDATA; a machine with no
25
- // provisioned payload simply has no file at that path and discoverShells skips
26
- // it per-candidate, exactly like a missing git-bash.exe link.
27
- import { existsSync, linkSync, mkdirSync, readdirSync, statSync } from "node:fs";
28
- import { join } from "node:path";
29
- import { spawnSync } from "node:child_process";
30
-
31
- /** The store layout for one env; pure, so tests can fake LOCALAPPDATA. */
32
- export function payloadAliasPaths(env) {
33
- const local = (env.LOCALAPPDATA ?? "").trim();
34
- if (local.length === 0) return undefined;
35
- const store = join(local, "dsh-bash-terminal-ts", "payloads");
36
- return {
37
- store,
38
- junction: join(store, "bash-terminal"),
39
- /** The stable candidate the bundle patch points at (junction + link name). */
40
- candidate: join(store, "bash-terminal", "bin", "bash-terminal.exe"),
41
- };
42
- }
43
-
44
- /** The newest provisioned root under the store (`posix-*` with bin/bash.exe). */
45
- export function findPayloadStoreRoot(store, readdir = readdirSync, exists = existsSync) {
46
- try {
47
- return readdir(store)
48
- .filter((name) => name.startsWith("posix-"))
49
- .filter((name) => exists(join(store, name, "bin", "bash.exe")))
50
- .sort()
51
- .pop();
52
- } catch {
53
- return undefined;
54
- }
55
- }
56
-
57
- /**
58
- * Create (idempotently) the hard link inside the root and the junction.
59
- * @param {{root: string, junction: string}} target root = a verified payload dir.
60
- * @returns {{link: string, junction: string, created: string[] , skipped?: string}}
61
- */
62
- export function ensurePayloadAlias(target, log = console.log) {
63
- const created = [];
64
- const source = join(target.root, "bin", "bash.exe");
65
- const link = join(target.root, "bin", "bash-terminal.exe");
66
- if (!existsSync(source)) {
67
- return { link, junction: target.junction, created, skipped: `no bin/bash.exe under ${target.root}` };
68
- }
69
- if (existsSync(link)) {
70
- const a = statSync(source);
71
- const b = statSync(link);
72
- if (a.ino !== b.ino || a.dev !== b.dev) {
73
- return { link, junction: target.junction, created, skipped: `${link} exists but is NOT a hard link of bash.exe` };
74
- }
75
- } else {
76
- linkSync(source, link);
77
- created.push(link);
78
- log(`created ${link}`);
79
- }
80
- // Junction: mklink /J via cmd (no privilege needed; works cross-volume).
81
- if (existsSync(target.junction)) {
82
- // A junction reads as a directory through existsSync; trust it if the
83
- // candidate resolves through it.
84
- if (existsSync(link.replace(target.root, join(target.junction, ""))) || existsSync(join(target.junction, "bin", "bash-terminal.exe"))) {
85
- return { link, junction: target.junction, created };
86
- }
87
- return { link, junction: target.junction, created, skipped: `${target.junction} exists but does not reach the payload bin` };
88
- }
89
- mkdirSync(target.store ?? join(target.junction, ".."), { recursive: true });
90
- const r = spawnSync("cmd", ["/c", "mklink", "/J", target.junction, target.root], { windowsHide: true, encoding: "utf8" });
91
- if (r.status !== 0) {
92
- return { link, junction: target.junction, created, skipped: `mklink /J failed (exit ${r.status}): ${(r.stderr ?? "").trim()}` };
93
- }
94
- created.push(target.junction);
95
- log(`created junction ${target.junction} -> ${target.root}`);
96
- return { link, junction: target.junction, created };
97
- }
@@ -1,233 +0,0 @@
1
- #!/usr/bin/env node
2
- // scripts/provision-payload.mjs - operator-side provisioning of the pinned
3
- // backup POSIX runtime payload for dsh-bash-terminal-ts.
4
- //
5
- // Naming: the artifact is OUR `posix-runtime` package - by policy our names
6
- // never carry the bash/gitbash/msys tokens (bare `bash` on Windows belongs to
7
- // the WSL forwarder's namespace; dsh-ops ships bash-*/msys-named payloads).
8
- // The tree inside is the Git-for-Windows runtime, unmodified - upstream facts
9
- // keep upstream file names.
10
- //
11
- // What this does: takes a LOCAL Git for Windows PortableGit SFX (or an already
12
- // extracted runtime directory), unpacks/accepts it, checks the runtime is real
13
- // (`bash --version`), computes SHA-256 of the two files the plugin's digest
14
- // gate reads (`bin/bash.exe`, `usr/bin/msys-2.0.dll`), and writes
15
- // `payload.trust.json` next to the root. From then on the plugin may run THAT
16
- // exact binary and nothing else: unknown or drifted digests fail closed.
17
- //
18
- // What this deliberately does NOT do:
19
- // - no downloads. The archive must exist on this machine (`--from`). We
20
- // repack upstream ourselves; we never consume dsh-ops's payload packages.
21
- // - no PATH / system changes. The payload lives under %LOCALAPPDATA% (or
22
- // wherever --into says) and is reachable only through the plugin.
23
- // - no silent promotion. Writing the trust file IS the human approval step;
24
- // --emit-ledger only prints a snippet, turning a local trust into a
25
- // shipped ledger entry stays a release-time code change.
26
- //
27
- // Usage:
28
- // node scripts/provision-payload.mjs --from "E:\dl\PortableGit-2.56.0.2-64-bit.7z.exe"
29
- // node scripts/provision-payload.mjs --from "D:\PortableGit" [--into <dir>] [--pack <dir>] [--emit-ledger] [--label <name>]
30
- import { spawnSync } from "node:child_process";
31
- import { createHash } from "node:crypto";
32
- import {
33
- copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync,
34
- statSync, writeFileSync
35
- } from "node:fs";
36
- import { join, resolve } from "node:path";
37
- import { parseArgs } from "node:util";
38
- import { ensurePayloadAlias, payloadAliasPaths } from "./payload-alias.mjs";
39
-
40
- const REQUIRED = [
41
- ["bin/bash.exe", "bin/bash.exe"],
42
- ["usr/bin/msys-2.0.dll", "usr/bin/msys-2.0.dll"]
43
- ];
44
-
45
- const { values: opt } = parseArgs({
46
- options: {
47
- from: { type: "string" },
48
- into: { type: "string" },
49
- label: { type: "string" },
50
- pack: { type: "string" },
51
- "emit-ledger": { type: "boolean", default: false },
52
- help: { type: "boolean", default: false }
53
- }
54
- });
55
-
56
- if (opt.help || !opt.from) {
57
- console.log(`usage: node scripts/provision-payload.mjs --from <PortableGit sfx | extracted dir>
58
- [--into <payload root>] [--label <build label>]
59
- [--pack <staging dir>] [--emit-ledger]`);
60
- process.exit(opt.help ? 0 : 2);
61
- }
62
-
63
- const from = resolve(opt.from);
64
- if (!existsSync(from)) fail(`--from does not exist: ${from}`);
65
-
66
- function fail(msg) {
67
- console.error(`provision-payload: ${msg}`);
68
- process.exit(1);
69
- }
70
-
71
- function sha256(file) {
72
- return createHash("sha256").update(readFileSync(file)).digest("hex");
73
- }
74
-
75
- // ---- 1. obtain a runtime root --------------------------------------------------
76
-
77
- let root;
78
- let sourceKind;
79
- const st = statSync(from);
80
- if (st.isFile()) {
81
- // 7-Zip SFX used by Git for Windows PortableGit: `-y -o<dir>` extracts, overwrite-all.
82
- const target = opt.into ? resolve(opt.into) : defaultStoreDir();
83
- if (target && existsSync(join(target, "bin", "bash.exe"))) {
84
- console.log(`payload root already unpacked at ${target}; re-verifying digests only (delete it to re-extract)`);
85
- root = target;
86
- sourceKind = "pre-extracted";
87
- } else {
88
- mkdirSync(target, { recursive: true });
89
- console.log(`extracting ${from} -> ${target} ...`);
90
- const r = spawnSync(from, ["-y", `-o${target}`], { windowsHide: true, stdio: "inherit" });
91
- if (r.error !== undefined || (r.status !== 0 && r.status !== 1 && r.status !== 2)) {
92
- fail(`SFX extraction failed (status=${r.status}, error=${r.error?.message ?? "none"})`);
93
- }
94
- if (!existsSync(join(target, "bin", "bash.exe"))) fail(`extraction produced no bin/bash.exe under ${target}`);
95
- root = target;
96
- sourceKind = "sfx";
97
- }
98
- } else if (st.isDirectory()) {
99
- root = from;
100
- sourceKind = "directory";
101
- if (opt.into) {
102
- // Copying a ~350 MB tree is the operator's explicit choice, never a side effect.
103
- const target = resolve(opt.into);
104
- if (!existsSync(join(target, "bin", "bash.exe"))) {
105
- fail(`--into ${target} is not a populated runtime directory; copying a payload tree is not automated here. Extract the SFX into it or point --into at an existing root.`);
106
- }
107
- root = target;
108
- }
109
- } else {
110
- fail(`--from must be an SFX file or a directory, got: ${from}`);
111
- }
112
-
113
- // ---- 2. the runtime must be real -------------------------------------------------
114
-
115
- const bashPath = join(root, "bin", "bash.exe");
116
- const dllPath = join(root, "usr", "bin", "msys-2.0.dll");
117
- for (const p of [bashPath, dllPath]) {
118
- if (!existsSync(p)) fail(`payload root is missing ${p}`);
119
- }
120
- const ver = spawnSync(bashPath, ["--version"], { encoding: "utf8", timeout: 15000, windowsHide: true });
121
- if (ver.error !== undefined || ver.status !== 0) {
122
- fail(`bin/bash.exe --version failed (status=${ver.status}, error=${ver.error?.message ?? "none"})`);
123
- }
124
- const versionLine = String(ver.stdout ?? "").split(/\r?\n/)[0] ?? "";
125
- const bashVersion = /version\s+(\S+)-release/.exec(versionLine)?.[1] ?? "unknown";
126
- console.log(`verified bash ${bashVersion} at ${bashPath}`);
127
-
128
- // ---- 3. digests + trust file ------------------------------------------------------
129
-
130
- const files = {};
131
- for (const [, rel] of REQUIRED) files[rel] = sha256(join(root, rel.replaceAll("/", "\\")));
132
- const label = opt.label ?? `posix-${bashVersion}-${new Date().toISOString().slice(0, 10)}`;
133
- const trustPath = join(root, "payload.trust.json");
134
- const trust = {
135
- schema: 1,
136
- label,
137
- bashVersion,
138
- files,
139
- source: { kind: sourceKind, path: from },
140
- provisionedAt: new Date().toISOString(),
141
- note: "operator-provisioned payload for dsh-bash-terminal-ts; digests pinned here are the ONLY version this plugin will run"
142
- };
143
- writeFileSync(trustPath, JSON.stringify(trust, null, 2) + "\n", "utf8");
144
- console.log(`trust record written: ${trustPath}`);
145
-
146
- // The official right-sidebar menu entry (hard link + stable junction). Only
147
- // reached after the runtime verified real, so the link can never point at an
148
- // unverified binary.
149
- {
150
- const paths = payloadAliasPaths(process.env);
151
- if (paths !== undefined) {
152
- const done = ensurePayloadAlias({ root, junction: paths.junction });
153
- if (done.skipped !== undefined) console.log(`NOTE: payload menu alias incomplete: ${done.skipped}`);
154
- else console.log(`menu alias ready: ${paths.candidate}`);
155
- }
156
- }
157
-
158
- // ---- 4. optional self-managed npm package ------------------------------------------
159
-
160
- if (opt.pack) {
161
- const staging = resolve(opt.pack);
162
- mkdirSync(staging, { recursive: true });
163
- const pkgDir = join(staging, "@drscrewdriver", "posix-runtime-win32-x64");
164
- mkdirSync(pkgDir, { recursive: true });
165
- // The WHOLE runtime tree travels, not just bin+usr: bash resolves its POSIX
166
- // root as <dir-of>/bin/../usr and sources <root>/etc/profile (`-lc` without
167
- // etc is a PATH-less shell). We regenerate the trust/provenance/package.json
168
- // ourselves, so copies of them inside the root are skipped.
169
- const SKIP = new Set(["payload.trust.json", "provenance.json", "package.json"]);
170
- for (const name of readdirSync(root)) {
171
- if (SKIP.has(name.toLowerCase())) continue;
172
- const s = join(root, name);
173
- const ist = statSync(s);
174
- if (ist.isDirectory()) cpTree(s, join(pkgDir, name));
175
- else if (ist.isFile()) copyFileSync(s, join(pkgDir, name));
176
- }
177
- const provenance = {
178
- label,
179
- upstream: "Git for Windows runtime tree, repacked by us unmodified - NOT dsh-ops's payload package",
180
- source: trust.source,
181
- bashVersion,
182
- files,
183
- packedAt: new Date().toISOString()
184
- };
185
- writeFileSync(join(pkgDir, "provenance.json"), JSON.stringify(provenance, null, 2) + "\n", "utf8");
186
- writeFileSync(join(pkgDir, "payload.trust.json"), JSON.stringify(trust, null, 2) + "\n", "utf8");
187
- writeFileSync(join(pkgDir, "package.json"), JSON.stringify({
188
- name: "@drscrewdriver/posix-runtime-win32-x64",
189
- version: "0.1.0",
190
- description: `Pinned POSIX runtime payload (Git-for-Windows tree) for dsh-bash-terminal-ts (win32-x64, bash ${bashVersion}). Contents: the upstream tree plus provenance/trust records; licenses travel with it.`,
191
- os: ["win32"],
192
- cpu: ["x64"],
193
- license: "SEE LICENSE IN LICENSE.txt",
194
- publishConfig: { registry: "https://registry.npmjs.org", access: "public" },
195
- dsh: { payload: { kind: "posix", bashVersion, label, digests: files } }
196
- }, null, 2) + "\n", "utf8");
197
- console.log(`package tree staged at ${pkgDir} (npm pack/publish is a separate, registry-pinned release step)`);
198
- }
199
-
200
- // ---- 5. ledger snippet --------------------------------------------------------------
201
-
202
- if (opt["emit-ledger"]) {
203
- console.log("\n// drop into src/payload.ts PAYLOAD_LEDGER (release-time edit, then rebuild):\n");
204
- console.log(` ${JSON.stringify(label)}: ${JSON.stringify(files)},`);
205
- }
206
-
207
- console.log(`\ndone. enable in the plugin config: enablePosixPayload: true${opt.into ? "" : ` (root: ${root})`}`);
208
-
209
- // ---- helpers ------------------------------------------------------------------------
210
-
211
- function defaultStoreDir() {
212
- const local = process.env.LOCALAPPDATA;
213
- if (!local) fail("no --into given and %LOCALAPPDATA% is unset - pass --into explicitly");
214
- const versionTag = bashVersionTagGuess();
215
- return join(local, "dsh-bash-terminal-ts", "payloads", `posix-${versionTag}`);
216
- }
217
-
218
- function bashVersionTagGuess() {
219
- // Before extraction we only have the archive name; fall back to a date tag.
220
- const m = /(\d+\.\d+\.\d+(?:\.\d+)?)/.exec(from);
221
- return m ? m[1] : new Date().toISOString().slice(0, 10);
222
- }
223
-
224
- function cpTree(src, dst) {
225
- mkdirSync(dst, { recursive: true });
226
- for (const name of readdirSync(src)) {
227
- const s = join(src, name);
228
- const d = join(dst, name);
229
- const ist = statSync(s);
230
- if (ist.isDirectory()) cpTree(s, d);
231
- else if (ist.isFile()) copyFileSync(s, d);
232
- }
233
- }
package/src/payload.ts DELETED
@@ -1,322 +0,0 @@
1
- // dsh-bash-terminal-ts: the pinned backup POSIX runtime payload - discovery
2
- // plus a fail-closed digest gate.
3
- //
4
- // Naming policy (operator decision, 2026-10): OUR artifacts never carry the
5
- // tokens `bash`, `gitbash` or `msys` - the bare name `bash` on Windows is the
6
- // WSL forwarder's territory, and dsh-ops ships `@dsh-ops/bash-*`/msys-named
7
- // payloads we must not shadow or be confused with. The runtime inside the
8
- // payload still IS Git-for-Windows (its binary is literally bash.exe - an
9
- // upstream fact, not our name); our namespace is `posix-runtime`.
10
- //
11
- // Why this exists: the plugin otherwise runs whatever Git Bash / MSYS2 the
12
- // machine happens to have, at whatever version the package manager left it at.
13
- // dsh-ops solved that by carrying its own pinned payload and refusing to run
14
- // anything whose digest it had not verified. We absorb the SEMANTICS (only an
15
- // executor whose SHA-256 is in a ledger we control may run), not the shipping
16
- // form: nothing is downloaded at install, no binary rides in the main tarball.
17
- // The payload is provisioned by the operator through
18
- // `scripts/provision-payload.mjs`, which reverse-unpacks a LOCAL PortableGit
19
- // SFX (our own repack of the upstream runtime - we never consume dsh-ops's
20
- // packages), records the digests, and drops a `payload.trust.json` beside it.
21
- //
22
- // The gate (fail-closed, on purpose):
23
- // - a root whose `bin/bash.exe` + `usr/bin/msys-2.0.dll` digests match the
24
- // embedded ledger or the local trust file is USABLE;
25
- // - anything else - unreadable, missing, unknown digest, mismatch after a
26
- // "was fine" state - is NOT. We never run an unverified bash, and we never
27
- // silently fall through to one: the reason surfaces as a note the plugin
28
- // logs once at startup. This matters MORE for us than for a confined
29
- // runner: MSYS bash cannot be wrapped by the DSH ACL restricted-token
30
- // sandbox (CreateFileMapping error 5), so digest verification is the only
31
- // security layer between us and the binary.
32
- //
33
- // The WSL preference rule (revised 2026-10 same day): a real WSL bash IS the
34
- // better POSIX shell, but once the payload became a first-class backend with a
35
- // double opt-in (operator gate + row switch), a hard veto made our own picker
36
- // stricter than the host's official menu, which lists bash-terminal.exe right
37
- // next to WSL's bash. So now: a detected WSL distro is an ADVISORY note, not a
38
- // gate. The digest gate remains the only hard no.
39
- //
40
- // Purity: every OS touch goes through the `PayloadProbe` seam so the whole
41
- // decision table is unit-testable without a payload on disk. The default probe
42
- // is the real fs/spawn one; hash results are memoized on (size, mtimeMs) so a
43
- // stable payload costs one re-read per change, per call.
44
-
45
- import { createHash } from "node:crypto";
46
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
47
- import { dirname, join } from "node:path";
48
- import { createRequire } from "node:module";
49
- import type * as ChildProcess from "node:child_process";
50
-
51
- /** npm package name of OUR POSIX runtime repack (optionalDependency-style; absent = simply no payload). */
52
- export const PAYLOAD_PACKAGE = "@drscrewdriver/posix-runtime-win32-x64";
53
- /** Trust record written next to a provisioned payload root by scripts/provision-payload.mjs. */
54
- export const TRUST_FILE_NAME = "payload.trust.json";
55
- /** Files every payload root must expose for verification, normalized to forward slashes, lowercase. */
56
- export const REQUIRED_FILES: readonly string[] = ["bin/bash.exe", "usr/bin/msys-2.0.dll"];
57
-
58
- /** One pinned payload build = one digest map. Keyed by the `posix-*` label. */
59
- export type DigestMap = Record<string, string>;
60
-
61
- /**
62
- * Built-in ledger, keyed by payload build label. Populated by
63
- * `provision-payload.mjs --emit-ledger` at release time (V-flow). EMPTY on a
64
- * fresh checkout by design: with no ledger entry, a root is only usable if the
65
- * operator's local trust file pins it - which is an explicit human act, the
66
- * same posture as `dsh-ops provision-shells` but self-managed.
67
- */
68
- export const PAYLOAD_LEDGER: Readonly<Record<string, DigestMap>> = {};
69
-
70
- export type PayloadVerdict =
71
- | { readonly ok: true; readonly bashPath: string; readonly source: "ledger" | "trust" }
72
- | { readonly ok: false; readonly reason: string };
73
-
74
- /** The OS face this module needs; tests substitute a table-driven fake. */
75
- export interface PayloadProbe {
76
- exists(path: string): boolean;
77
- read(path: string): Buffer | undefined;
78
- /** `size|mtimeMs` fingerprint for the hash cache, or undefined when unstatable. */
79
- stamp(path: string): string | undefined;
80
- readdir(dir: string): string[];
81
- /** Directory holding `package.json` of PAYLOAD_PACKAGE, if installed. */
82
- resolvePackageRoot(): string | undefined;
83
- /**
84
- * WSL distro probe: names of installed distros, or undefined when the probe
85
- * cannot answer (undefined is NOT "no distro" - absence needs a positive
86
- * empty list, same three-valued rule as the browser catalog's distros fact).
87
- */
88
- wslDistros(): readonly string[] | undefined;
89
- }
90
-
91
- /** Environment directory carrying auto-discovered payload roots. */
92
- export function payloadStoreDir(env: NodeJS.ProcessEnv = process.env): string | undefined {
93
- const localAppData = env.LOCALAPPDATA;
94
- if (typeof localAppData !== "string" || localAppData.trim().length === 0) return undefined;
95
- return join(localAppData, "dsh-bash-terminal-ts", "payloads");
96
- }
97
-
98
- // ---- default probe (real fs / wsl) --------------------------------------------
99
-
100
- const defaultProbe: PayloadProbe = {
101
- exists: (p) => {
102
- try {
103
- return existsSync(p);
104
- } catch {
105
- return false;
106
- }
107
- },
108
- read: (p) => {
109
- try {
110
- return readFileSync(p);
111
- } catch {
112
- return undefined;
113
- }
114
- },
115
- stamp: (p) => {
116
- try {
117
- const st = statSync(p);
118
- return `${st.size}|${st.mtimeMs}`;
119
- } catch {
120
- return undefined;
121
- }
122
- },
123
- readdir: (d) => {
124
- try {
125
- return readdirSync(d);
126
- } catch {
127
- return [];
128
- }
129
- },
130
- resolvePackageRoot: () => {
131
- try {
132
- const req = createRequire(import.meta.url);
133
- return dirname(req.resolve(`${PAYLOAD_PACKAGE}/package.json`));
134
- } catch {
135
- return undefined;
136
- }
137
- },
138
- wslDistros: () => {
139
- try {
140
- // The child_process face is loaded lazily so importers that never touch
141
- // the default probe (browser-side graphs, pure unit tests with an
142
- // injected probe) do not pull it in; spawnSync with a short timeout:
143
- // `wsl -l -q` is fast when WSL is present and hangs (or errors) when it
144
- // is a stub, which is exactly the "cannot answer" case.
145
- const { spawnSync } = require_child_process();
146
- // wsl.exe writes UTF-16LE (measured: "Ubuntu" arrives as U\0b\0u\0...),
147
- // so `encoding: "utf8"` would turn an EMPTY distro list into one
148
- // mojibake line - a false "WSL has a distro" that would veto the
149
- // payload on machines that have none. Read bytes and decode by shape:
150
- // NUL interleaving means UTF-16LE, everything else is ascii/utf8.
151
- const r = spawnSync("wsl.exe", ["-l", "-q"], { timeout: 5000, windowsHide: true });
152
- if (r.error !== undefined || r.status === null || !Buffer.isBuffer(r.stdout)) return undefined;
153
- const raw: Buffer = r.stdout;
154
- const text = raw.includes(0x00) ? raw.toString("utf16le") : raw.toString("utf8");
155
- const names = text.split(/\r?\n/).map((l) => l.replaceAll("\u0000", "").trim()).filter((l) => l.length > 0);
156
- return names;
157
- } catch {
158
- return undefined;
159
- }
160
- }
161
- };
162
-
163
- // Type-only import above, runtime require here: the module reference is erased
164
- // at compile time, so the host graph stays free of a static child_process edge.
165
- function require_child_process(): typeof ChildProcess {
166
- return createRequire(import.meta.url)("node:child_process") as typeof ChildProcess;
167
- }
168
-
169
- // ---- hashing -------------------------------------------------------------------
170
-
171
- const hashCache = new Map<string, { stamp: string; sha: string }>();
172
-
173
- /** sha256 hex of one file, memoized on (size, mtimeMs); undefined when unreadable. */
174
- export function hashFile(path: string, probe: PayloadProbe = defaultProbe): string | undefined {
175
- const stamp = probe.stamp(path);
176
- if (stamp === undefined) return undefined;
177
- const hit = hashCache.get(path);
178
- if (hit !== undefined && hit.stamp === stamp) return hit.sha;
179
- const buf = probe.read(path);
180
- if (buf === undefined) return undefined;
181
- const sha = createHash("sha256").update(buf).digest("hex");
182
- hashCache.set(path, { stamp, sha });
183
- return sha;
184
- }
185
-
186
- /** Test/backdoor: drop the memo (a payload replaced in place must re-verify). */
187
- export function clearHashCache(): void {
188
- hashCache.clear();
189
- }
190
-
191
- // ---- verification ----------------------------------------------------------------
192
-
193
- function normalizeRel(p: string): string {
194
- return p.replaceAll("\\", "/").toLowerCase();
195
- }
196
-
197
- function digestMapsMatch(actual: Record<string, string | undefined>, pinned: DigestMap): boolean {
198
- const keys = Object.keys(pinned);
199
- if (keys.length === 0) return false;
200
- return keys.every((k) => {
201
- const want = pinned[k];
202
- const got = actual[normalizeRel(k)];
203
- return typeof want === "string" && typeof got === "string" && want.toLowerCase() === got;
204
- });
205
- }
206
-
207
- /**
208
- * Verify one payload root: both REQUIRED_FILES exist, their digests match the
209
- * built-in ledger OR the root-local trust file. Everything else fails closed.
210
- */
211
- export function verifyPayloadRoot(root: string, probe: PayloadProbe = defaultProbe): PayloadVerdict {
212
- const bashPath = join(root, "bin", "bash.exe");
213
- const dllPath = join(root, "usr", "bin", "msys-2.0.dll");
214
- if (!probe.exists(root)) return { ok: false, reason: `missing-root:${root}` };
215
- if (!probe.exists(bashPath) || !probe.exists(dllPath)) {
216
- return { ok: false, reason: `missing-files:${root}` };
217
- }
218
- const actual: Record<string, string | undefined> = {
219
- "bin/bash.exe": hashFile(bashPath, probe),
220
- "usr/bin/msys-2.0.dll": hashFile(dllPath, probe)
221
- };
222
- if (Object.values(actual).some((v) => v === undefined)) {
223
- return { ok: false, reason: `unreadable:${root}` };
224
- }
225
- for (const pinned of Object.values(PAYLOAD_LEDGER)) {
226
- if (digestMapsMatch(actual, pinned)) return { ok: true, bashPath, source: "ledger" };
227
- }
228
- const trustRaw = probe.read(join(root, TRUST_FILE_NAME));
229
- if (trustRaw !== undefined) {
230
- let trust: unknown;
231
- try {
232
- trust = JSON.parse(trustRaw.toString("utf8"));
233
- } catch {
234
- return { ok: false, reason: `trust-unparsed:${root}` };
235
- }
236
- const files = (trust as { files?: unknown }).files;
237
- if (files !== null && typeof files === "object") {
238
- const map: DigestMap = {};
239
- for (const [k, v] of Object.entries(files as Record<string, unknown>)) {
240
- if (typeof v === "string") map[normalizeRel(k)] = v.toLowerCase();
241
- }
242
- // The trust file must pin EVERY required file, or it does not constitute
243
- // an approval of the executor we are about to run.
244
- if (REQUIRED_FILES.every((f) => f in map) && digestMapsMatch(actual, map)) {
245
- return { ok: true, bashPath, source: "trust" };
246
- }
247
- }
248
- return { ok: false, reason: `digest-mismatch:${root}` };
249
- }
250
- return { ok: false, reason: `digest-unknown:${root}` };
251
- }
252
-
253
- // ---- root discovery ----------------------------------------------------------------
254
-
255
- /** Candidate payload roots in preference order: explicit path, npm package, store dir. */
256
- export function findPayloadRoots(
257
- config: { payloadBashPath?: string },
258
- probe: PayloadProbe = defaultProbe,
259
- env: NodeJS.ProcessEnv = process.env
260
- ): string[] {
261
- const roots: string[] = [];
262
- const push = (r: string | undefined) => {
263
- if (typeof r === "string" && r.trim().length > 0 && !roots.includes(r)) roots.push(r);
264
- };
265
- const explicit = (config.payloadBashPath ?? "").trim();
266
- if (explicit.length > 0 && /bash\.exe$/i.test(explicit)) push(dirname(dirname(explicit)));
267
- else if (explicit.length > 0) push(explicit); // a root directory is also honoured
268
- push(probe.resolvePackageRoot());
269
- const store = payloadStoreDir(env);
270
- if (store !== undefined) {
271
- for (const child of probe.readdir(store)) {
272
- const full = join(store, child);
273
- if (probe.exists(join(full, "bin", "bash.exe"))) push(full);
274
- }
275
- }
276
- return roots;
277
- }
278
-
279
- export interface PayloadOutcome {
280
- /** True only when a verified payload bash was selected. */
281
- readonly engaged: boolean;
282
- readonly bashPath?: string;
283
- /** True when a WSL distro was positively detected - advisory, not a veto. */
284
- readonly wslPreferred?: boolean;
285
- /** One-shot human-readable notes for the plugin log. */
286
- readonly notes: readonly string[];
287
- }
288
-
289
- /**
290
- * The whole decision table for one startup. Call ONLY when the payload feature
291
- * is enabled; the caller wires the resulting `bashPath` into the gitbash slot
292
- * of `resolveAllPaths` as the last-resort source.
293
- */
294
- export function resolvePayloadBash(
295
- config: { payloadBashPath?: string },
296
- probe: PayloadProbe = defaultProbe,
297
- env: NodeJS.ProcessEnv = process.env
298
- ): PayloadOutcome {
299
- const notes: string[] = [];
300
- const distros = probe.wslDistros();
301
- const wslPreferred = distros !== undefined && distros.length > 0;
302
- if (wslPreferred) {
303
- notes.push(
304
- `posix-payload: WSL distro(s) detected (${distros.slice(0, 3).join(", ")}) - a real WSL bash is usually the better POSIX shell, prefer the "wsl" backend when in doubt. The payload stays selectable; this is a hint, not a gate.`
305
- );
306
- }
307
- const roots = findPayloadRoots(config, probe, env);
308
- if (roots.length === 0) {
309
- notes.push("posix-payload: enabled but no payload root found (provision one with scripts/provision-payload.mjs or set payloadPosixPath).");
310
- return { engaged: false, wslPreferred, notes };
311
- }
312
- const failures: string[] = [];
313
- for (const root of roots) {
314
- const verdict = verifyPayloadRoot(root, probe);
315
- if (verdict.ok) {
316
- return { engaged: true, bashPath: verdict.bashPath, wslPreferred, notes };
317
- }
318
- failures.push(verdict.reason);
319
- }
320
- notes.push(`posix-payload: every candidate root failed the digest gate, fail-closed (not run): ${failures.join("; ")}`);
321
- return { engaged: false, wslPreferred, notes };
322
- }