@verax-ai/body 0.4.1 → 0.4.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.
package/dist/install.js CHANGED
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { EX_CONFIG } from "./config.js";
9
9
  import { INSTALL_HEALTH_NONCE } from "./health-extras.js";
10
10
  import { runInitLocal } from "./init-local.js";
11
+ import { psModuleImports } from "./ps-module-imports.js";
11
12
  export const EX_ELEVATION = 77;
12
13
  export const ELEVATION_LINE = "verax install needs an elevated shell (Administrator / root)";
13
14
  const POSIX_CLI = "/opt/verax-cli/lib/node_modules/@verax-ai/body/dist/cli.js";
@@ -209,6 +210,7 @@ function expandMachineRoot(raw, drive, label) {
209
210
  }
210
211
  const MACHINE_ROOTS_SCRIPT = [
211
212
  "$ErrorActionPreference = 'Stop'",
213
+ psModuleImports(["Microsoft.PowerShell.Management"]),
212
214
  "$files = (Get-Item -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion').GetValue('ProgramFilesDir', $null, 'DoNotExpandEnvironmentNames')",
213
215
  "$data = (Get-Item -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList').GetValue('ProgramData', $null, 'DoNotExpandEnvironmentNames')",
214
216
  "$root = (Get-Item -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion').GetValue('SystemRoot', $null, 'DoNotExpandEnvironmentNames')",
@@ -265,6 +267,7 @@ function assertAdminWritableTree(root, exec) {
265
267
  * Absolute path for a system tool. Windows uses System32 under SystemRoot.
266
268
  * Linux walks fixed directories and never consults PATH.
267
269
  * macOS uses the fixed table (dscl, launchctl, chown, chmod, id, stat, plutil, lsof).
270
+ * `ls` is the POSIX ACL reader at `/bin/ls`, not an install-plan tool, so it is not in that table.
268
271
  * A missing Linux binary falls back to the first candidate so a plan can name
269
272
  * the path; spawning still refuses when that file is absent.
270
273
  */
@@ -278,6 +281,8 @@ export function systemToolPath(tool, platform = process.platform) {
278
281
  return path.win32.join(root, "System32", `${name}.exe`);
279
282
  }
280
283
  if (platform === "darwin") {
284
+ if (name === "ls")
285
+ return "/bin/ls";
281
286
  const fixed = DARWIN_TOOL_PATHS[name];
282
287
  if (!fixed)
283
288
  throw new SystemToolError(`refusing: ${name} is not a macOS install tool`);
@@ -907,7 +912,7 @@ export function windowsSddlArgv(target) {
907
912
  "-NoProfile",
908
913
  "-NonInteractive",
909
914
  "-Command",
910
- `(Get-Acl -LiteralPath '${literal}').Sddl`,
915
+ psPrefixed(["Microsoft.PowerShell.Security"], `(Get-Acl -LiteralPath '${literal}').Sddl`),
911
916
  ], "win32");
912
917
  }
913
918
  function uniquePaths(paths) {
@@ -934,11 +939,15 @@ export function windowsSddlBatchStdin(paths) {
934
939
  * object: `{ "<path>": "<sddl>" | { "error": "<msg>" } }`.
935
940
  * PowerShell 5.1 unwraps a one-element JSON array, so the script re-wraps with
936
941
  * `| ForEach-Object { $_ }`.
942
+ * JSON cmdlets are loaded with psModuleImports before first use. #119, measured
943
+ * on windows-full 5a75875: autoload of ConvertFrom-Json took 23 to 30 s on a
944
+ * GitHub Windows runner, and 0.27 s once the module was loaded from System32 first.
937
945
  */
938
946
  export function windowsSddlBatchArgv(paths) {
939
947
  // Intentionally unused. Interpolating `paths` here is the overflow F17b closes.
940
948
  void paths;
941
949
  const script = `$ErrorActionPreference = 'Stop'
950
+ ${psModuleImports(["Microsoft.PowerShell.Utility"])}
942
951
  $utf8 = New-Object System.Text.UTF8Encoding $false
943
952
  [Console]::InputEncoding = $utf8
944
953
  [Console]::OutputEncoding = $utf8
@@ -949,10 +958,15 @@ $result = @{}
949
958
  foreach ($p in $paths) {
950
959
  $key = [string]$p
951
960
  try {
952
- $acl = Get-Acl -LiteralPath $key
953
- $result[$key] = [string]$acl.Sddl
961
+ if ([System.IO.Directory]::Exists($key)) {
962
+ $sec = [System.IO.Directory]::GetAccessControl($key)
963
+ } else {
964
+ $sec = [System.IO.File]::GetAccessControl($key)
965
+ }
966
+ $result[$key] = [string]$sec.GetSecurityDescriptorSddlForm('All')
954
967
  } catch {
955
- $err = @{ error = [string]$_.Exception.Message }
968
+ $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }
969
+ $err = @{ error = [string]$e.Message }
956
970
  $result[$key] = $err
957
971
  }
958
972
  }
@@ -1357,11 +1371,262 @@ export function posixOthersCanReplace(st, ancestor) {
1357
1371
  return false;
1358
1372
  return !(ancestor && (st.mode & 0o1000) !== 0);
1359
1373
  }
1360
- /** POSIX half of the elevated code check. `read` supplies uid and mode so a test does not lstat the machine. */
1361
- export function posixCodeDirectoryDetail(dir, platform, read) {
1374
+ /** macOS ACL rights that let someone replace or rewrite an entry. Deny entries are not rights. */
1375
+ const DARWIN_ACL_WRITE = new Set([
1376
+ "write",
1377
+ "append",
1378
+ "add_file",
1379
+ "add_subdirectory",
1380
+ "delete",
1381
+ "delete_child",
1382
+ "writeattr",
1383
+ "writeextattr",
1384
+ "writesecurity",
1385
+ "chown",
1386
+ ]);
1387
+ /**
1388
+ * Text for a POSIX ACL refusal, or null when the extended ACL adds no writer.
1389
+ * `"unreadable"` is fail-closed: Linux showed `+` and `getfacl` did not return the entries.
1390
+ * The phrase is what the operator sees: install acl or remove the ACL.
1391
+ */
1392
+ export function posixAclWriterDetail(found) {
1393
+ if (found === undefined)
1394
+ return null;
1395
+ if (found === "unreadable")
1396
+ return "install acl or remove the ACL";
1397
+ if (found.length === 0)
1398
+ return null;
1399
+ return found.join(", ");
1400
+ }
1401
+ function aclMap(paths, value) {
1402
+ const map = new Map();
1403
+ for (const file of paths)
1404
+ map.set(file, value);
1405
+ return map;
1406
+ }
1407
+ /** Longest requested path that is the final field of an `ls` line. */
1408
+ function pathOnLsLine(line, paths) {
1409
+ let best = null;
1410
+ for (const file of paths) {
1411
+ if (file.length === 0 || !line.endsWith(file))
1412
+ continue;
1413
+ const at = line.length - file.length;
1414
+ if (at > 0 && line[at - 1] !== " ")
1415
+ continue;
1416
+ if (!best || file.length > best.length)
1417
+ best = file;
1418
+ }
1419
+ return best;
1420
+ }
1421
+ function darwinAclSkipped(principal, owner) {
1422
+ const colon = principal.indexOf(":");
1423
+ const tag = colon < 0 ? principal : principal.slice(0, colon);
1424
+ const name = colon < 0 ? "" : principal.slice(colon + 1);
1425
+ if (tag === "owner")
1426
+ return true;
1427
+ if (tag === "user" && (name === "root" || (owner !== "" && name === owner)))
1428
+ return true;
1429
+ if (tag === "group" && name === "admin")
1430
+ return true;
1431
+ return false;
1432
+ }
1433
+ function darwinRightsAllowWrite(rights) {
1434
+ for (const token of rights.split(/[,\s]+/)) {
1435
+ if (DARWIN_ACL_WRITE.has(token))
1436
+ return true;
1437
+ }
1438
+ return false;
1439
+ }
1440
+ /** One `ls -lde` listing. A failed process is unreadable. A clean listing with no allow-write is empty. */
1441
+ function parseDarwinAcl(stdout, paths) {
1442
+ const map = new Map();
1443
+ const owners = new Map();
1444
+ for (const file of paths)
1445
+ map.set(file, []);
1446
+ let current = null;
1447
+ for (const raw of stdout.split(/\r?\n/)) {
1448
+ const ace = /^\s*\d+:\s+(\S+)\s+(?:inherited\s+)?(allow|deny)\s+(\S.*)$/.exec(raw);
1449
+ if (ace) {
1450
+ if (!current || ace[2] !== "allow")
1451
+ continue;
1452
+ const list = map.get(current);
1453
+ if (!list || list === "unreadable")
1454
+ continue;
1455
+ if (darwinAclSkipped(ace[1], owners.get(current) ?? ""))
1456
+ continue;
1457
+ if (!darwinRightsAllowWrite(ace[3]))
1458
+ continue;
1459
+ if (!list.includes(ace[1]))
1460
+ list.push(ace[1]);
1461
+ continue;
1462
+ }
1463
+ // A listing starts with the mode. ACE lines are indented, so they do not.
1464
+ if (!/^[bcdlps-][r-][w-][sStTx-][r-][w-][sStTx-][r-][w-][tTx-][@+]?[\s]/.test(raw))
1465
+ continue;
1466
+ const hit = pathOnLsLine(raw.trimEnd(), paths);
1467
+ if (!hit)
1468
+ continue;
1469
+ current = hit;
1470
+ const fields = raw.trim().split(/\s+/);
1471
+ owners.set(hit, fields[2] ?? "");
1472
+ if (!map.has(hit))
1473
+ map.set(hit, []);
1474
+ }
1475
+ return map;
1476
+ }
1477
+ function writersInGetfaclBlock(block) {
1478
+ let mask = null;
1479
+ const named = [];
1480
+ for (const raw of block.split(/\n/)) {
1481
+ const line = raw.trim();
1482
+ if (line === "" || line.startsWith("#") || line.startsWith("default:"))
1483
+ continue;
1484
+ const maskLine = /^mask::([r-][w-][x-])/.exec(line);
1485
+ if (maskLine) {
1486
+ mask = maskLine[1] ?? null;
1487
+ continue;
1488
+ }
1489
+ const entry = /^(user|group):([^:]+):([r-][w-][x-])/.exec(line);
1490
+ if (!entry)
1491
+ continue;
1492
+ named.push({ who: `${entry[1]}:${entry[2]}`, perm: entry[3] ?? "" });
1493
+ }
1494
+ const writers = [];
1495
+ for (const entry of named) {
1496
+ if (entry.perm[1] !== "w")
1497
+ continue;
1498
+ if (mask !== null && mask[1] !== "w")
1499
+ continue;
1500
+ writers.push(entry.who);
1501
+ }
1502
+ return writers;
1503
+ }
1504
+ /** `getfacl -cp` blocks, in argument order, or `# file:` groups when a header is still present. */
1505
+ function parseGetfacl(stdout, paths) {
1506
+ const text = stdout.replace(/\r\n/g, "\n");
1507
+ if (/^# file:/m.test(text)) {
1508
+ const map = new Map();
1509
+ for (const part of text.split(/^# file:\s*/m).slice(1)) {
1510
+ const nl = part.indexOf("\n");
1511
+ const header = (nl < 0 ? part : part.slice(0, nl)).trim();
1512
+ const body = nl < 0 ? "" : part.slice(nl + 1);
1513
+ const file = paths.find((candidate) => candidate === header) ?? pathOnLsLine(header, paths);
1514
+ if (!file)
1515
+ continue;
1516
+ map.set(file, writersInGetfaclBlock(body));
1517
+ }
1518
+ for (const file of paths)
1519
+ if (!map.has(file))
1520
+ map.set(file, "unreadable");
1521
+ return map;
1522
+ }
1523
+ const blocks = text.split(/\n[ \t]*\n/).map((block) => block.trim()).filter((block) => block !== "");
1524
+ if (blocks.length !== paths.length)
1525
+ return aclMap(paths, "unreadable");
1526
+ const map = new Map();
1527
+ for (let i = 0; i < paths.length; i += 1)
1528
+ map.set(paths[i], writersInGetfaclBlock(blocks[i]));
1529
+ return map;
1530
+ }
1531
+ function linuxPlusPaths(stdout, paths) {
1532
+ const plus = [];
1533
+ const seen = new Set();
1534
+ for (const raw of stdout.split(/\r?\n/)) {
1535
+ const line = raw.trim();
1536
+ if (line === "")
1537
+ continue;
1538
+ const mode = line.split(/\s+/)[0] ?? "";
1539
+ if (!/^[bcdlps-]/.test(mode))
1540
+ continue;
1541
+ const hit = pathOnLsLine(line, paths);
1542
+ if (!hit || seen.has(hit))
1543
+ continue;
1544
+ seen.add(hit);
1545
+ if (mode.endsWith("+") || mode.includes("+"))
1546
+ plus.push(hit);
1547
+ }
1548
+ return plus;
1549
+ }
1550
+ /**
1551
+ * Extended ACL writers for every path, from one `ls` (and on Linux one `getfacl` for the `+` paths).
1552
+ * macOS: `allow` entries with a write right, except the file owner, `user:root`, and `group:admin`.
1553
+ * `deny` is ignored. `inherited` still counts.
1554
+ * Linux: a named `user:` or `group:` with `w` that the `mask` also allows.
1555
+ * `getfacl` missing while `ls` shows `+` is `"unreadable"` (fail closed).
1556
+ * A non-zero `ls` is `"unreadable"` too: the `+` could not be seen.
1557
+ * Exit 0 with no `+` is an empty list.
1558
+ */
1559
+ export function posixAclWriters(paths, platform, exec) {
1560
+ const wanted = uniquePaths(paths);
1561
+ if (wanted.length === 0)
1562
+ return new Map();
1563
+ if (platform !== "darwin" && platform !== "linux")
1564
+ return aclMap(wanted, []);
1565
+ if (platform === "darwin") {
1566
+ let argv;
1567
+ try {
1568
+ argv = toolArgv("ls", ["-lde", "--", ...wanted], "darwin");
1569
+ }
1570
+ catch {
1571
+ return aclMap(wanted, "unreadable");
1572
+ }
1573
+ const ran = exec(argv);
1574
+ if ((ran.status ?? 1) !== 0)
1575
+ return aclMap(wanted, "unreadable");
1576
+ return parseDarwinAcl(ran.stdout ?? "", wanted);
1577
+ }
1578
+ let lsArgv;
1579
+ try {
1580
+ lsArgv = toolArgv("ls", ["-ld", "--", ...wanted], "linux");
1581
+ }
1582
+ catch {
1583
+ return aclMap(wanted, "unreadable");
1584
+ }
1585
+ const listed = exec(lsArgv);
1586
+ if ((listed.status ?? 1) !== 0)
1587
+ return aclMap(wanted, "unreadable");
1588
+ const plus = linuxPlusPaths(listed.stdout ?? "", wanted);
1589
+ const map = aclMap(wanted, []);
1590
+ if (plus.length === 0)
1591
+ return map;
1592
+ let getfaclArgv;
1593
+ try {
1594
+ getfaclArgv = toolArgv("getfacl", ["-cp", "--", ...plus], "linux");
1595
+ }
1596
+ catch {
1597
+ for (const file of plus)
1598
+ map.set(file, "unreadable");
1599
+ return map;
1600
+ }
1601
+ const read = exec(getfaclArgv);
1602
+ if ((read.status ?? 1) !== 0) {
1603
+ for (const file of plus)
1604
+ map.set(file, "unreadable");
1605
+ return map;
1606
+ }
1607
+ const parsed = parseGetfacl(read.stdout ?? "", plus);
1608
+ for (const file of plus)
1609
+ map.set(file, parsed.get(file) ?? "unreadable");
1610
+ return map;
1611
+ }
1612
+ /**
1613
+ * POSIX half of the elevated code check. `read` supplies uid and mode so a test does not lstat the machine.
1614
+ * `acls` is the one `posixAclWriters` map for this trust list. When mode says the entry is safe, a writer
1615
+ * or `"unreadable"` is still a refusal. Omit `acls` only when the caller is injecting modes and not ACLs.
1616
+ */
1617
+ export function posixCodeDirectoryDetail(dir, platform, read, acls) {
1362
1618
  for (const file of trustTargets(dir, platform)) {
1363
1619
  const st = read(file.path);
1364
1620
  if (st !== null && !posixOthersCanReplace({ uid: st.uid, mode: st.mode, symlink: st.symlink === true }, file.ancestor)) {
1621
+ if (acls) {
1622
+ const found = acls.has(file.path) ? acls.get(file.path) : "unreadable";
1623
+ const detail = posixAclWriterDetail(found);
1624
+ if (detail) {
1625
+ return found === "unreadable"
1626
+ ? `${file.path} ACL could not be read (${detail})`
1627
+ : `${file.path} ACL ${detail}`;
1628
+ }
1629
+ }
1365
1630
  continue;
1366
1631
  }
1367
1632
  if (st === null)
@@ -1555,14 +1820,20 @@ export function powerShellScript(body) {
1555
1820
  function psNative(command, tool) {
1556
1821
  return `${command}; if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("${PS_ERROR_MARK} ${tool} exited $LASTEXITCODE"); exit $LASTEXITCODE }`;
1557
1822
  }
1558
- function windowsAccountOps(password, create, tempDir) {
1823
+ function windowsAccountBody(create, tempDir) {
1559
1824
  const user = create
1560
1825
  ? "New-LocalUser -Name 'verax-svc' -Password $sec -PasswordNeverExpires -UserMayNotChangePassword -AccountNeverExpires -Description 'Verax body service account'"
1561
1826
  : "Set-LocalUser -Name 'verax-svc' -Password $sec";
1562
1827
  const cfg = psSingle(path.win32.join(tempDir, "verax-rights.cfg"));
1563
1828
  const db = psSingle(path.win32.join(tempDir, "verax-rights.sdb"));
1564
1829
  const after = psSingle(path.win32.join(tempDir, "verax-rights-after.cfg"));
1565
- const script = [
1830
+ return [
1831
+ psModuleImports([
1832
+ "Microsoft.PowerShell.Security",
1833
+ "Microsoft.PowerShell.LocalAccounts",
1834
+ "Microsoft.PowerShell.Management",
1835
+ "Microsoft.PowerShell.Utility",
1836
+ ]),
1566
1837
  "$plain = [Console]::In.ReadLine()",
1567
1838
  "if ([string]::IsNullOrEmpty($plain)) { exit 1 }",
1568
1839
  "$sec = ConvertTo-SecureString -String $plain -AsPlainText -Force",
@@ -1600,11 +1871,18 @@ function windowsAccountOps(password, create, tempDir) {
1600
1871
  "[Console]::Out.WriteLine(('SeBatchLogonRight: ' + $gotSet.Count + ' holders, service account added'))",
1601
1872
  "Remove-Item $cfg,$db,$after -ErrorAction SilentlyContinue",
1602
1873
  ].join("; ");
1603
- return [powershellStdin(script, password, tempDir)];
1604
1874
  }
1605
- function windowsTaskOp(password, nodeBin, cliBin, envFile, logFile, tempDir) {
1875
+ function windowsAccountOps(password, create, tempDir) {
1876
+ return [powershellStdin(windowsAccountBody(create, tempDir), password, tempDir)];
1877
+ }
1878
+ function windowsTaskBody(nodeBin, cliBin, envFile, logFile) {
1606
1879
  const argument = `"${cliBin}" serve --env-file "${envFile}" --log-file "${logFile}"`;
1607
- const script = [
1880
+ return [
1881
+ psModuleImports([
1882
+ "ScheduledTasks",
1883
+ "Microsoft.PowerShell.Utility",
1884
+ "Microsoft.PowerShell.LocalAccounts",
1885
+ ]),
1608
1886
  "$plain = [Console]::In.ReadLine()",
1609
1887
  "if ([string]::IsNullOrEmpty($plain)) { exit 1 }",
1610
1888
  `$action = New-ScheduledTaskAction -Execute ${psSingle(nodeBin)} -Argument ${psSingle(argument)}`,
@@ -1614,7 +1892,50 @@ function windowsTaskOp(password, nodeBin, cliBin, envFile, logFile, tempDir) {
1614
1892
  "Register-ScheduledTask -TaskName 'Verax Body' -Action $action -Trigger $trigger -User $sid -Password $plain -RunLevel Limited -Settings $settings -Force",
1615
1893
  "Start-ScheduledTask -TaskName 'Verax Body'",
1616
1894
  ].join("; ");
1617
- return powershellStdin(script, password, tempDir);
1895
+ }
1896
+ function windowsTaskOp(password, nodeBin, cliBin, envFile, logFile, tempDir) {
1897
+ return powershellStdin(windowsTaskBody(nodeBin, cliBin, envFile, logFile), password, tempDir);
1898
+ }
1899
+ /** Module import lines, then `command` unchanged. */
1900
+ function psPrefixed(modules, command) {
1901
+ return `${psModuleImports(modules)}\n${command}`;
1902
+ }
1903
+ function aclOwnerCommand(dir) {
1904
+ const literal = dir.replaceAll("'", "''");
1905
+ return psPrefixed(["Microsoft.PowerShell.Security"], `(Get-Acl -LiteralPath '${literal}').Owner`);
1906
+ }
1907
+ function directoryOwnerSidCommand(dir) {
1908
+ const literal = dir.replaceAll("'", "''");
1909
+ return psPrefixed(["Microsoft.PowerShell.Security"], `(Get-Acl -LiteralPath '${literal}').GetOwner([System.Security.Principal.SecurityIdentifier]).Value`);
1910
+ }
1911
+ const WINDOWS_SERVICE_SID_COMMAND = psPrefixed(["Microsoft.PowerShell.LocalAccounts"], "(Get-LocalUser -Name 'verax-svc').SID.Value");
1912
+ function profileImagePathCommand(sid) {
1913
+ return psPrefixed(["Microsoft.PowerShell.Management"], `(Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}').ProfileImagePath`);
1914
+ }
1915
+ /**
1916
+ * Every PowerShell -Command install.ts runs, with sample paths.
1917
+ * Call sites: readWindowsMachineRoots, windowsSddlArgv, windowsSddlBatchArgv,
1918
+ * powershellStdin (account create, account update, scheduled task), ownerModeLine,
1919
+ * the service SID lookup in execute, directoryOwnerSid, the ProfileImagePath lookup,
1920
+ * and windowsServiceSid. desktop.ts local account SIDs are a separate command.
1921
+ */
1922
+ export function windowsPowerShellScripts() {
1923
+ const temp = "C:\\ProgramData\\Verax\\install-tmp";
1924
+ return [
1925
+ { id: "machine-roots", script: MACHINE_ROOTS_SCRIPT },
1926
+ { id: "sddl", script: windowsSddlArgv("C:\\ProgramData\\Verax").at(-1) ?? "" },
1927
+ { id: "sddl-batch", script: windowsSddlBatchArgv(["C:\\ProgramData\\Verax"]).at(-1) ?? "" },
1928
+ { id: "acl-owner", script: aclOwnerCommand("C:\\ProgramData\\Verax") },
1929
+ { id: "directory-owner-sid", script: directoryOwnerSidCommand("C:\\ProgramData\\Verax") },
1930
+ { id: "service-sid", script: WINDOWS_SERVICE_SID_COMMAND },
1931
+ { id: "profile-image-path", script: profileImagePathCommand("S-1-5-21-1001") },
1932
+ { id: "account-create", script: powerShellScript(windowsAccountBody(true, temp)) },
1933
+ { id: "account-update", script: powerShellScript(windowsAccountBody(false, temp)) },
1934
+ {
1935
+ id: "scheduled-task",
1936
+ script: powerShellScript(windowsTaskBody("C:\\Program Files\\nodejs\\node.exe", "C:\\Program Files\\Verax\\node_modules\\@verax-ai\\body\\dist\\cli.js", "C:\\ProgramData\\Verax\\state\\body.env", "C:\\ProgramData\\Verax\\state\\body.log")),
1937
+ },
1938
+ ];
1618
1939
  }
1619
1940
  function xmlEscape(value) {
1620
1941
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
@@ -1808,6 +2129,7 @@ function readInstallAncestor(dir, read) {
1808
2129
  }
1809
2130
  }
1810
2131
  function installAncestorPlanRefusal(platform, codeDir, stateDir, unitOrPlist, read) {
2132
+ const safe = [];
1811
2133
  for (const dir of posixInstallAncestorDirs(platform, codeDir, stateDir, unitOrPlist)) {
1812
2134
  const st = readInstallAncestor(dir, read);
1813
2135
  if (st === "missing")
@@ -1815,10 +2137,23 @@ function installAncestorPlanRefusal(platform, codeDir, stateDir, unitOrPlist, re
1815
2137
  if (st === "unreadable") {
1816
2138
  return fail(EX_CONFIG, `refusing: ${dir} can be changed by other users (owner uid unknown, mode unknown); the service code under it could be replaced`);
1817
2139
  }
1818
- if (!posixOthersCanReplace(st, true))
2140
+ if (posixOthersCanReplace(st, true)) {
2141
+ const mode = (st.mode & 0o7777).toString(8);
2142
+ return fail(EX_CONFIG, `refusing: ${dir} can be changed by other users (owner uid ${st.uid}, mode ${mode}); the service code under it could be replaced`);
2143
+ }
2144
+ safe.push(dir);
2145
+ }
2146
+ // Injected ancestor stats stand in for the live tree, including its ACLs.
2147
+ // Production lstats, then reads every mode-safe ancestor in one posixAclWriters call.
2148
+ if (read || safe.length === 0)
2149
+ return null;
2150
+ const acls = posixAclWriters(safe, platform, defaultExec);
2151
+ for (const dir of safe) {
2152
+ const found = acls.has(dir) ? acls.get(dir) : "unreadable";
2153
+ const detail = posixAclWriterDetail(found);
2154
+ if (!detail)
1819
2155
  continue;
1820
- const mode = (st.mode & 0o7777).toString(8);
1821
- return fail(EX_CONFIG, `refusing: ${dir} can be changed by other users (owner uid ${st.uid}, mode ${mode}); the service code under it could be replaced`);
2156
+ return fail(EX_CONFIG, `refusing: ${dir} can be changed by other users (${detail}); the service code under it could be replaced`);
1822
2157
  }
1823
2158
  return null;
1824
2159
  }
@@ -2982,7 +3317,7 @@ function ownerModeLine(platform, dir, exec) {
2982
3317
  const ran = exec(toolArgv("powershell", [
2983
3318
  "-NoProfile",
2984
3319
  "-Command",
2985
- `(Get-Acl -LiteralPath '${dir.replaceAll("'", "''")}').Owner`,
3320
+ aclOwnerCommand(dir),
2986
3321
  ], "win32"));
2987
3322
  const owner = (ran.stdout ?? "").trim().split(/\r?\n/).filter((line) => line.trim() !== "").pop() ?? (ran.stderr ?? "").trim();
2988
3323
  return `${owner} ntfs ${dir}`;
@@ -3786,7 +4121,7 @@ async function execute(plan, exec, io, platform, copyFile = copyFileSync, instal
3786
4121
  const ran = call(toolArgv("powershell", [
3787
4122
  "-NoProfile",
3788
4123
  "-Command",
3789
- "(Get-LocalUser -Name 'verax-svc').SID.Value",
4124
+ WINDOWS_SERVICE_SID_COMMAND,
3790
4125
  ], "win32"));
3791
4126
  svcSid = (ran.stdout ?? "").match(/S-1-[0-9-]+/)?.[0] ?? "";
3792
4127
  if (svcSid === "")
@@ -4296,11 +4631,10 @@ function directoryOwnerSid(dir, exec) {
4296
4631
  const cached = winOwnerCache?.owners;
4297
4632
  if (cached?.has(dir))
4298
4633
  return cached.get(dir);
4299
- const literal = dir.replaceAll("'", "''");
4300
4634
  const ran = exec(toolArgv("powershell", [
4301
4635
  "-NoProfile",
4302
4636
  "-Command",
4303
- `(Get-Acl -LiteralPath '${literal}').GetOwner([System.Security.Principal.SecurityIdentifier]).Value`,
4637
+ directoryOwnerSidCommand(dir),
4304
4638
  ], "win32"));
4305
4639
  const sid = (ran.status ?? 1) !== 0 ? undefined : `${ran.stdout ?? ""}`.match(/S-1-[0-9-]+/i)?.[0];
4306
4640
  cached?.set(dir, sid);
@@ -4603,6 +4937,8 @@ function collectTarballs(dirArg, platform, exec, io, sddl = null) {
4603
4937
  */
4604
4938
  function codeDirsWritable(dirs, platform, exec) {
4605
4939
  if (platform !== "win32") {
4940
+ const targets = dirs.flatMap((dir) => trustTargets(dir, platform));
4941
+ const acls = posixAclWriters(targets.map((file) => file.path), platform, exec);
4606
4942
  return (dir) => posixCodeDirectoryDetail(dir, platform, (file) => {
4607
4943
  try {
4608
4944
  const st = lstatSync(file);
@@ -4611,7 +4947,7 @@ function codeDirsWritable(dirs, platform, exec) {
4611
4947
  catch {
4612
4948
  return null;
4613
4949
  }
4614
- });
4950
+ }, acls);
4615
4951
  }
4616
4952
  const sid = invokingSid(exec);
4617
4953
  const read = readSddlBatch(exec, dirs.flatMap((dir) => trustTargets(dir, "win32").map((file) => file.path)));
@@ -4646,6 +4982,7 @@ export function elevatedPreloadRefusal(env, execArgv) {
4646
4982
  function nodeBinaryUntrusted(platform, execPath, exec, probe) {
4647
4983
  const files = trustTargets(execPath, platform);
4648
4984
  let hit = null;
4985
+ let aclNote = null;
4649
4986
  if (probe) {
4650
4987
  for (const file of files) {
4651
4988
  if (probe(file.path) && hit === null)
@@ -4670,14 +5007,24 @@ function nodeBinaryUntrusted(platform, execPath, exec, probe) {
4670
5007
  }
4671
5008
  }
4672
5009
  else {
5010
+ const acls = posixAclWriters(files.map((file) => file.path), platform, exec);
4673
5011
  for (const file of files) {
4674
5012
  if (posixEntryUntrusted(file.path, file.ancestor)) {
4675
5013
  hit = file.path;
4676
5014
  break;
4677
5015
  }
5016
+ const detail = posixAclWriterDetail(acls.has(file.path) ? acls.get(file.path) : "unreadable");
5017
+ if (detail) {
5018
+ hit = file.path;
5019
+ aclNote = detail;
5020
+ break;
5021
+ }
4678
5022
  }
4679
5023
  }
4680
- return hit === null ? null : nodeTrustMessageFor(hit, platform);
5024
+ if (hit === null)
5025
+ return null;
5026
+ const message = nodeTrustMessageFor(hit, platform);
5027
+ return aclNote ? `${message} (${aclNote})` : message;
4681
5028
  }
4682
5029
  export function refuseWritableCode(platform, env, exec, probe, node) {
4683
5030
  if (platform !== "win32" && platform !== "linux" && platform !== "darwin")
@@ -4751,7 +5098,9 @@ function invokingUserCanChangeState(dir, platform, env) {
4751
5098
  }
4752
5099
  const uidText = env.SUDO_UID?.trim() ?? "";
4753
5100
  const invokingUid = /^\d+$/.test(uidText) ? Number(uidText) : null;
4754
- for (const file of trustTargets(dir, spec)) {
5101
+ const files = trustTargets(dir, spec);
5102
+ const safe = [];
5103
+ for (const file of files) {
4755
5104
  let st;
4756
5105
  try {
4757
5106
  st = lstatSync(file.path);
@@ -4762,15 +5111,25 @@ function invokingUserCanChangeState(dir, platform, env) {
4762
5111
  if (posixStateUntrusted({ uid: st.uid, mode: st.mode, symlink: st.isSymbolicLink() }, file.ancestor, invokingUid)) {
4763
5112
  return true;
4764
5113
  }
5114
+ safe.push(file.path);
5115
+ }
5116
+ if (safe.length === 0)
5117
+ return false;
5118
+ const acls = posixAclWriters(safe, spec, defaultExec);
5119
+ for (const file of safe) {
5120
+ const detail = posixAclWriterDetail(acls.has(file) ? acls.get(file) : "unreadable");
5121
+ if (detail)
5122
+ return detail;
4765
5123
  }
4766
5124
  return false;
4767
5125
  }
4768
5126
  /** Elevated approve opens a state directory only when the invoking user cannot change it. */
4769
5127
  export function elevatedStateDirRefusal(dir, platform, env, probe) {
4770
5128
  const writable = probe ? probe(dir) : invokingUserCanChangeState(dir, platform, env);
4771
- if (!writable)
5129
+ if (writable === false)
4772
5130
  return null;
4773
- return `refusing: ${dir} can be changed by ${codeTrustAccount(platform, env)}; an elevated approve only opens the installed state directory`;
5131
+ const extra = typeof writable === "string" ? ` (${writable})` : "";
5132
+ return `refusing: ${dir} can be changed by ${codeTrustAccount(platform, env)}; an elevated approve only opens the installed state directory${extra}`;
4774
5133
  }
4775
5134
  /**
4776
5135
  * Set by the CLI after one passing code check, so install and approve do not
@@ -5000,12 +5359,18 @@ async function runInstallBody(argv, hooks = {}) {
5000
5359
  }
5001
5360
  }
5002
5361
  else {
5362
+ const acls = posixAclWriters(trustFiles.map((file) => file.path), trustPlat, exec);
5003
5363
  for (const file of trustFiles) {
5364
+ const said = isModuleSearchDir(file.path) ? moduleDirTrustMessage(file.path, trustPlat) : nodeTrustMessageFor(file.path, trustPlat);
5004
5365
  if (posixEntryUntrusted(file.path, file.ancestor)) {
5005
- const said = isModuleSearchDir(file.path) ? moduleDirTrustMessage(file.path, trustPlat) : nodeTrustMessageFor(file.path, trustPlat);
5006
5366
  io.stderr.write(`${said}\n`);
5007
5367
  return EX_CONFIG;
5008
5368
  }
5369
+ const detail = posixAclWriterDetail(acls.has(file.path) ? acls.get(file.path) : "unreadable");
5370
+ if (detail) {
5371
+ io.stderr.write(`${said} (${detail})\n`);
5372
+ return EX_CONFIG;
5373
+ }
5009
5374
  }
5010
5375
  }
5011
5376
  }
@@ -5081,7 +5446,7 @@ async function runInstallBody(argv, hooks = {}) {
5081
5446
  const looked = exec(toolArgv("powershell", [
5082
5447
  "-NoProfile",
5083
5448
  "-Command",
5084
- `(Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}').ProfileImagePath`,
5449
+ profileImagePathCommand(sid),
5085
5450
  ], "win32"));
5086
5451
  // The agent token no longer lives in the profile (R14-8), so an unreadable
5087
5452
  // ProfileImagePath is not a refusal; a readable one that disagrees still is.
@@ -5276,7 +5641,7 @@ function windowsServiceSid(exec) {
5276
5641
  "-NoProfile",
5277
5642
  "-NonInteractive",
5278
5643
  "-Command",
5279
- "(Get-LocalUser -Name 'verax-svc').SID.Value",
5644
+ WINDOWS_SERVICE_SID_COMMAND,
5280
5645
  ], "win32"));
5281
5646
  if ((ran.status ?? 1) !== 0)
5282
5647
  return null;
@@ -10,6 +10,7 @@ export type CredentialStore = {
10
10
  credentials: StoredCredential[];
11
11
  };
12
12
  export declare function credentialsPath(stateDir: string): string;
13
+ export declare function readCredentialsAt(path: string): StoredCredential[];
13
14
  export declare function readCredentials(stateDir: string): StoredCredential[];
14
15
  /**
15
16
  * The file is written only when an operator enrolls, so its presence is the
@@ -6,8 +6,7 @@ export const DEFAULT_OPERATOR_SUB = "operator-1";
6
6
  export function credentialsPath(stateDir) {
7
7
  return join(stateDir, CREDENTIALS_FILE);
8
8
  }
9
- export function readCredentials(stateDir) {
10
- const path = credentialsPath(stateDir);
9
+ export function readCredentialsAt(path) {
11
10
  if (!existsSync(path))
12
11
  return [];
13
12
  try {
@@ -23,6 +22,9 @@ export function readCredentials(stateDir) {
23
22
  return [];
24
23
  }
25
24
  }
25
+ export function readCredentials(stateDir) {
26
+ return readCredentialsAt(credentialsPath(stateDir));
27
+ }
26
28
  /**
27
29
  * The file is written only when an operator enrolls, so its presence is the
28
30
  * answer. Asking whether it parses would read a truncated or mistyped file as
@@ -0,0 +1,17 @@
1
+ /**
2
+ * System32 module directory loads for PowerShell started with systemToolEnv().
3
+ *
4
+ * #119, measured on windows-full 5a75875: under that environment PSModulePath is
5
+ * only the System32 Windows PowerShell 5.1 module directory, and resolving an
6
+ * autoloaded cmdlet (ConvertFrom-Json) took 23 to 30 s on a GitHub Windows
7
+ * runner. Import-Module of the same module by its System32 path took 0.27 s.
8
+ * Each statement names the module directory. LocalAccounts lives in a version
9
+ * subdirectory (1.0.0.0 on the measured Windows 11 machine); importing the
10
+ * directory lets Windows PowerShell choose that version and stay inside System32.
11
+ */
12
+ export declare const PS_MODULES: readonly ["Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Management", "Microsoft.PowerShell.Security", "Microsoft.PowerShell.LocalAccounts", "ScheduledTasks"];
13
+ export type PsModule = (typeof PS_MODULES)[number];
14
+ /** One Import-Module statement. The expected line shape lives only here. */
15
+ export declare function psModuleImportLine(module: PsModule): string;
16
+ /** One line per module, in the given order. A repeated module is emitted once. */
17
+ export declare function psModuleImports(modules: readonly PsModule[]): string;