@verax-ai/body 0.4.0 → 0.4.2

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`);
@@ -315,7 +320,9 @@ export const PS_ERROR_MARK = "verax-ps-error:";
315
320
  * AppData directory and must not receive install files.
316
321
  * On Windows, PSModulePath is only the System32 Windows PowerShell 5.1 module
317
322
  * directory. Without it, PowerShell 5.1 puts Documents\WindowsPowerShell\Modules
318
- * first, and -NoProfile does not change that list.
323
+ * first, and -NoProfile does not change that list. PowerShell 5.1 still inserts
324
+ * Program Files\WindowsPowerShell\Modules in front of the pinned value (measured
325
+ * on 5.1.26100); the install trust-checks that directory as an object.
319
326
  */
320
327
  export function systemToolEnv(platform = process.platform, tempDir) {
321
328
  if (platform === "win32") {
@@ -504,6 +511,23 @@ function officialNodeRemedy(platform) {
504
511
  export function nodeTrustMessage(nodePath) {
505
512
  return `Node at ${nodePath} can be changed by your user account; install Node for all users (nodejs.org installer) and run verax install from that Node`;
506
513
  }
514
+ /** A directory Node or PowerShell searches for code to load, judged apart from Node itself. */
515
+ function isModuleSearchDir(file) {
516
+ const trimmed = file.replace(/[\\/]+$/, "");
517
+ return /(^|[\\/])node_modules$/i.test(trimmed) || /[\\/]WindowsPowerShell[\\/]Modules$/i.test(trimmed);
518
+ }
519
+ /**
520
+ * The remedy for a module directory is that directory, not a different Node:
521
+ * a user-writable /usr/local/lib/node_modules refuses every Node under /usr/local/lib.
522
+ */
523
+ function moduleDirTrustMessage(dir, platform) {
524
+ const head = `Module directory ${dir} can be changed by your user account. An elevated install loads code from it, so the install refuses it`;
525
+ if (platform === "win32") {
526
+ return `${head}. Remove it, or leave it writable only by Administrators and SYSTEM, then run verax install again`;
527
+ }
528
+ const owner = platform === "darwin" ? "root:wheel" : "root:root";
529
+ return `${head}. Remove it, or make it ${owner} and not group- or other-writable (sudo chown -R ${owner} ${dir}; sudo chmod -R go-w ${dir}), then run verax install again`;
530
+ }
507
531
  function nodeTrustMessageFor(nodePath, platform) {
508
532
  const head = `Node at ${nodePath} can be changed by your user account`;
509
533
  if (platform === "win32")
@@ -574,6 +598,10 @@ export function veraxCodeDirectories(entryUrl = import.meta.url) {
574
598
  return [];
575
599
  add(body);
576
600
  add(path.join(body, "node_modules"));
601
+ // Node also searches every ancestor's node_modules, up to the drive root.
602
+ const hostFlavor = process.platform === "win32" ? "win32" : "linux";
603
+ for (const dir of moduleSearchDirs(body, hostFlavor))
604
+ add(dir);
577
605
  let deps = [];
578
606
  try {
579
607
  const parsed = JSON.parse(readFileSync(path.join(body, "package.json"), "utf8"));
@@ -884,7 +912,7 @@ export function windowsSddlArgv(target) {
884
912
  "-NoProfile",
885
913
  "-NonInteractive",
886
914
  "-Command",
887
- `(Get-Acl -LiteralPath '${literal}').Sddl`,
915
+ psPrefixed(["Microsoft.PowerShell.Security"], `(Get-Acl -LiteralPath '${literal}').Sddl`),
888
916
  ], "win32");
889
917
  }
890
918
  function uniquePaths(paths) {
@@ -911,11 +939,15 @@ export function windowsSddlBatchStdin(paths) {
911
939
  * object: `{ "<path>": "<sddl>" | { "error": "<msg>" } }`.
912
940
  * PowerShell 5.1 unwraps a one-element JSON array, so the script re-wraps with
913
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.
914
945
  */
915
946
  export function windowsSddlBatchArgv(paths) {
916
947
  // Intentionally unused. Interpolating `paths` here is the overflow F17b closes.
917
948
  void paths;
918
949
  const script = `$ErrorActionPreference = 'Stop'
950
+ ${psModuleImports(["Microsoft.PowerShell.Utility"])}
919
951
  $utf8 = New-Object System.Text.UTF8Encoding $false
920
952
  [Console]::InputEncoding = $utf8
921
953
  [Console]::OutputEncoding = $utf8
@@ -926,10 +958,15 @@ $result = @{}
926
958
  foreach ($p in $paths) {
927
959
  $key = [string]$p
928
960
  try {
929
- $acl = Get-Acl -LiteralPath $key
930
- $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')
931
967
  } catch {
932
- $err = @{ error = [string]$_.Exception.Message }
968
+ $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }
969
+ $err = @{ error = [string]$e.Message }
933
970
  $result[$key] = $err
934
971
  }
935
972
  }
@@ -1292,6 +1329,33 @@ export function trustTargets(file, platform) {
1292
1329
  ancestor: parentIsObject ? index > 1 : index > 0,
1293
1330
  }));
1294
1331
  }
1332
+ /**
1333
+ * The `node_modules` directories Node searches for a bare specifier that code
1334
+ * under `start` imports: `<dir>/node_modules` for `start` and every parent, up
1335
+ * to the root, skipping a directory that is itself named `node_modules`.
1336
+ * Stock Windows lets any authenticated user create a folder under `C:\`, so
1337
+ * `C:\node_modules` can be planted beside an elevated or service Node. Each
1338
+ * one that exists is judged as an object (add-file counts). A missing one is
1339
+ * not listed: the loader skips it, and refusing every machine for a folder
1340
+ * that is not there would refuse them all.
1341
+ */
1342
+ export function moduleSearchDirs(start, platform, exists = existsSync) {
1343
+ const p = platform === "win32" ? path.win32 : path.posix;
1344
+ const out = [];
1345
+ let cur = p.normalize(start);
1346
+ for (;;) {
1347
+ if (p.basename(cur).toLowerCase() !== "node_modules") {
1348
+ const candidate = p.join(cur, "node_modules");
1349
+ if (exists(candidate))
1350
+ out.push(candidate);
1351
+ }
1352
+ const parent = p.dirname(cur);
1353
+ if (parent === cur)
1354
+ break;
1355
+ cur = parent;
1356
+ }
1357
+ return out;
1358
+ }
1295
1359
  /**
1296
1360
  * Another user can rename or replace this entry.
1297
1361
  * An ancestor with the sticky bit is kept: only its owner can rename a child (mode 1777, the way `/tmp` works).
@@ -1307,11 +1371,262 @@ export function posixOthersCanReplace(st, ancestor) {
1307
1371
  return false;
1308
1372
  return !(ancestor && (st.mode & 0o1000) !== 0);
1309
1373
  }
1310
- /** POSIX half of the elevated code check. `read` supplies uid and mode so a test does not lstat the machine. */
1311
- 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) {
1312
1618
  for (const file of trustTargets(dir, platform)) {
1313
1619
  const st = read(file.path);
1314
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
+ }
1315
1630
  continue;
1316
1631
  }
1317
1632
  if (st === null)
@@ -1505,14 +1820,20 @@ export function powerShellScript(body) {
1505
1820
  function psNative(command, tool) {
1506
1821
  return `${command}; if ($LASTEXITCODE -ne 0) { [Console]::Error.WriteLine("${PS_ERROR_MARK} ${tool} exited $LASTEXITCODE"); exit $LASTEXITCODE }`;
1507
1822
  }
1508
- function windowsAccountOps(password, create, tempDir) {
1823
+ function windowsAccountBody(create, tempDir) {
1509
1824
  const user = create
1510
1825
  ? "New-LocalUser -Name 'verax-svc' -Password $sec -PasswordNeverExpires -UserMayNotChangePassword -AccountNeverExpires -Description 'Verax body service account'"
1511
1826
  : "Set-LocalUser -Name 'verax-svc' -Password $sec";
1512
1827
  const cfg = psSingle(path.win32.join(tempDir, "verax-rights.cfg"));
1513
1828
  const db = psSingle(path.win32.join(tempDir, "verax-rights.sdb"));
1514
1829
  const after = psSingle(path.win32.join(tempDir, "verax-rights-after.cfg"));
1515
- const script = [
1830
+ return [
1831
+ psModuleImports([
1832
+ "Microsoft.PowerShell.Security",
1833
+ "Microsoft.PowerShell.LocalAccounts",
1834
+ "Microsoft.PowerShell.Management",
1835
+ "Microsoft.PowerShell.Utility",
1836
+ ]),
1516
1837
  "$plain = [Console]::In.ReadLine()",
1517
1838
  "if ([string]::IsNullOrEmpty($plain)) { exit 1 }",
1518
1839
  "$sec = ConvertTo-SecureString -String $plain -AsPlainText -Force",
@@ -1550,11 +1871,18 @@ function windowsAccountOps(password, create, tempDir) {
1550
1871
  "[Console]::Out.WriteLine(('SeBatchLogonRight: ' + $gotSet.Count + ' holders, service account added'))",
1551
1872
  "Remove-Item $cfg,$db,$after -ErrorAction SilentlyContinue",
1552
1873
  ].join("; ");
1553
- return [powershellStdin(script, password, tempDir)];
1554
1874
  }
1555
- 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) {
1556
1879
  const argument = `"${cliBin}" serve --env-file "${envFile}" --log-file "${logFile}"`;
1557
- const script = [
1880
+ return [
1881
+ psModuleImports([
1882
+ "ScheduledTasks",
1883
+ "Microsoft.PowerShell.Utility",
1884
+ "Microsoft.PowerShell.LocalAccounts",
1885
+ ]),
1558
1886
  "$plain = [Console]::In.ReadLine()",
1559
1887
  "if ([string]::IsNullOrEmpty($plain)) { exit 1 }",
1560
1888
  `$action = New-ScheduledTaskAction -Execute ${psSingle(nodeBin)} -Argument ${psSingle(argument)}`,
@@ -1564,7 +1892,50 @@ function windowsTaskOp(password, nodeBin, cliBin, envFile, logFile, tempDir) {
1564
1892
  "Register-ScheduledTask -TaskName 'Verax Body' -Action $action -Trigger $trigger -User $sid -Password $plain -RunLevel Limited -Settings $settings -Force",
1565
1893
  "Start-ScheduledTask -TaskName 'Verax Body'",
1566
1894
  ].join("; ");
1567
- 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
+ ];
1568
1939
  }
1569
1940
  function xmlEscape(value) {
1570
1941
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
@@ -1758,6 +2129,7 @@ function readInstallAncestor(dir, read) {
1758
2129
  }
1759
2130
  }
1760
2131
  function installAncestorPlanRefusal(platform, codeDir, stateDir, unitOrPlist, read) {
2132
+ const safe = [];
1761
2133
  for (const dir of posixInstallAncestorDirs(platform, codeDir, stateDir, unitOrPlist)) {
1762
2134
  const st = readInstallAncestor(dir, read);
1763
2135
  if (st === "missing")
@@ -1765,10 +2137,23 @@ function installAncestorPlanRefusal(platform, codeDir, stateDir, unitOrPlist, re
1765
2137
  if (st === "unreadable") {
1766
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`);
1767
2139
  }
1768
- 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)
1769
2155
  continue;
1770
- const mode = (st.mode & 0o7777).toString(8);
1771
- 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`);
1772
2157
  }
1773
2158
  return null;
1774
2159
  }
@@ -2932,7 +3317,7 @@ function ownerModeLine(platform, dir, exec) {
2932
3317
  const ran = exec(toolArgv("powershell", [
2933
3318
  "-NoProfile",
2934
3319
  "-Command",
2935
- `(Get-Acl -LiteralPath '${dir.replaceAll("'", "''")}').Owner`,
3320
+ aclOwnerCommand(dir),
2936
3321
  ], "win32"));
2937
3322
  const owner = (ran.stdout ?? "").trim().split(/\r?\n/).filter((line) => line.trim() !== "").pop() ?? (ran.stderr ?? "").trim();
2938
3323
  return `${owner} ntfs ${dir}`;
@@ -3736,7 +4121,7 @@ async function execute(plan, exec, io, platform, copyFile = copyFileSync, instal
3736
4121
  const ran = call(toolArgv("powershell", [
3737
4122
  "-NoProfile",
3738
4123
  "-Command",
3739
- "(Get-LocalUser -Name 'verax-svc').SID.Value",
4124
+ WINDOWS_SERVICE_SID_COMMAND,
3740
4125
  ], "win32"));
3741
4126
  svcSid = (ran.stdout ?? "").match(/S-1-[0-9-]+/)?.[0] ?? "";
3742
4127
  if (svcSid === "")
@@ -4246,11 +4631,10 @@ function directoryOwnerSid(dir, exec) {
4246
4631
  const cached = winOwnerCache?.owners;
4247
4632
  if (cached?.has(dir))
4248
4633
  return cached.get(dir);
4249
- const literal = dir.replaceAll("'", "''");
4250
4634
  const ran = exec(toolArgv("powershell", [
4251
4635
  "-NoProfile",
4252
4636
  "-Command",
4253
- `(Get-Acl -LiteralPath '${literal}').GetOwner([System.Security.Principal.SecurityIdentifier]).Value`,
4637
+ directoryOwnerSidCommand(dir),
4254
4638
  ], "win32"));
4255
4639
  const sid = (ran.status ?? 1) !== 0 ? undefined : `${ran.stdout ?? ""}`.match(/S-1-[0-9-]+/i)?.[0];
4256
4640
  cached?.set(dir, sid);
@@ -4553,6 +4937,8 @@ function collectTarballs(dirArg, platform, exec, io, sddl = null) {
4553
4937
  */
4554
4938
  function codeDirsWritable(dirs, platform, exec) {
4555
4939
  if (platform !== "win32") {
4940
+ const targets = dirs.flatMap((dir) => trustTargets(dir, platform));
4941
+ const acls = posixAclWriters(targets.map((file) => file.path), platform, exec);
4556
4942
  return (dir) => posixCodeDirectoryDetail(dir, platform, (file) => {
4557
4943
  try {
4558
4944
  const st = lstatSync(file);
@@ -4561,7 +4947,7 @@ function codeDirsWritable(dirs, platform, exec) {
4561
4947
  catch {
4562
4948
  return null;
4563
4949
  }
4564
- });
4950
+ }, acls);
4565
4951
  }
4566
4952
  const sid = invokingSid(exec);
4567
4953
  const read = readSddlBatch(exec, dirs.flatMap((dir) => trustTargets(dir, "win32").map((file) => file.path)));
@@ -4587,11 +4973,16 @@ export function elevatedPreloadRefusal(env, execArgv) {
4587
4973
  if (options.trim() !== "" || flagged) {
4588
4974
  return "refusing: NODE_OPTIONS or a preload flag is set; an elevated verax runs with none";
4589
4975
  }
4976
+ // NODE_PATH adds the caller's directories to the module search list of an elevated process.
4977
+ if ((env.NODE_PATH ?? "").trim() !== "") {
4978
+ return "refusing: NODE_PATH is set; an elevated verax resolves modules only from its own install";
4979
+ }
4590
4980
  return null;
4591
4981
  }
4592
4982
  function nodeBinaryUntrusted(platform, execPath, exec, probe) {
4593
4983
  const files = trustTargets(execPath, platform);
4594
4984
  let hit = null;
4985
+ let aclNote = null;
4595
4986
  if (probe) {
4596
4987
  for (const file of files) {
4597
4988
  if (probe(file.path) && hit === null)
@@ -4616,14 +5007,24 @@ function nodeBinaryUntrusted(platform, execPath, exec, probe) {
4616
5007
  }
4617
5008
  }
4618
5009
  else {
5010
+ const acls = posixAclWriters(files.map((file) => file.path), platform, exec);
4619
5011
  for (const file of files) {
4620
5012
  if (posixEntryUntrusted(file.path, file.ancestor)) {
4621
5013
  hit = file.path;
4622
5014
  break;
4623
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
+ }
4624
5022
  }
4625
5023
  }
4626
- 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;
4627
5028
  }
4628
5029
  export function refuseWritableCode(platform, env, exec, probe, node) {
4629
5030
  if (platform !== "win32" && platform !== "linux" && platform !== "darwin")
@@ -4697,7 +5098,9 @@ function invokingUserCanChangeState(dir, platform, env) {
4697
5098
  }
4698
5099
  const uidText = env.SUDO_UID?.trim() ?? "";
4699
5100
  const invokingUid = /^\d+$/.test(uidText) ? Number(uidText) : null;
4700
- for (const file of trustTargets(dir, spec)) {
5101
+ const files = trustTargets(dir, spec);
5102
+ const safe = [];
5103
+ for (const file of files) {
4701
5104
  let st;
4702
5105
  try {
4703
5106
  st = lstatSync(file.path);
@@ -4708,15 +5111,25 @@ function invokingUserCanChangeState(dir, platform, env) {
4708
5111
  if (posixStateUntrusted({ uid: st.uid, mode: st.mode, symlink: st.isSymbolicLink() }, file.ancestor, invokingUid)) {
4709
5112
  return true;
4710
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;
4711
5123
  }
4712
5124
  return false;
4713
5125
  }
4714
5126
  /** Elevated approve opens a state directory only when the invoking user cannot change it. */
4715
5127
  export function elevatedStateDirRefusal(dir, platform, env, probe) {
4716
5128
  const writable = probe ? probe(dir) : invokingUserCanChangeState(dir, platform, env);
4717
- if (!writable)
5129
+ if (writable === false)
4718
5130
  return null;
4719
- 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}`;
4720
5133
  }
4721
5134
  /**
4722
5135
  * Set by the CLI after one passing code check, so install and approve do not
@@ -4878,6 +5291,10 @@ async function runInstallBody(argv, hooks = {}) {
4878
5291
  trustFiles.push(...trustTargets(path.win32.join(sys, "System32"), "win32"));
4879
5292
  for (const name of WIN32_TOOLS)
4880
5293
  trustFiles.push(...trustTargets(winToolUnder(sys, name), "win32"));
5294
+ // PowerShell 5.1 autoloads from here before System32, whatever PSModulePath says.
5295
+ const sharedModules = path.win32.join(filesRoot, "WindowsPowerShell", "Modules");
5296
+ if ((hooks.moduleDirExists ?? existsSync)(sharedModules))
5297
+ trustFiles.push(...trustTargets(sharedModules, "win32"));
4881
5298
  // The install roots are parents of what the installer creates and locks, and stock ProgramData lets Users create
4882
5299
  // folders. They are judged by the ancestor rule (no write-DAC, owner or delete-child for a non-admin), not as objects.
4883
5300
  for (const root of [data, filesRoot]) {
@@ -4892,6 +5309,23 @@ async function runInstallBody(argv, hooks = {}) {
4892
5309
  throw err;
4893
5310
  }
4894
5311
  }
5312
+ if (trustPlat) {
5313
+ // npm (run by this install) and the installed body resolve bare specifiers
5314
+ // through every ancestor's node_modules. Each one on disk is judged as an object.
5315
+ const moduleExists = hooks.moduleDirExists ?? existsSync;
5316
+ const starts = [
5317
+ (trustPlat === "win32" ? path.win32 : path.posix).dirname(layout.npmCli),
5318
+ codeDirFor(trustPlat, plannedEnv, posixRoot, adopted),
5319
+ ];
5320
+ const seen = new Set();
5321
+ for (const dir of starts.flatMap((start) => moduleSearchDirs(start, trustPlat, moduleExists))) {
5322
+ const key = trustPlat === "win32" ? dir.toLowerCase() : dir;
5323
+ if (seen.has(key))
5324
+ continue;
5325
+ seen.add(key);
5326
+ trustFiles.push(...trustTargets(dir, trustPlat));
5327
+ }
5328
+ }
4895
5329
  let sddlPlan = null;
4896
5330
  if (platform === "win32") {
4897
5331
  const root = path.win32.dirname(stateDir);
@@ -4918,15 +5352,23 @@ async function runInstallBody(argv, hooks = {}) {
4918
5352
  for (const file of trustFiles) {
4919
5353
  const acl = sddlOrMiss(cache, file.path);
4920
5354
  if (acl.status !== 0 || windowsUserCanWrite(acl.text, { path: file.path, userSid: sid, ancestor: file.ancestor })) {
4921
- io.stderr.write(`${refuseAcl(acl.text, nodeTrustMessage(file.path))}\n`);
5355
+ const said = isModuleSearchDir(file.path) ? moduleDirTrustMessage(file.path, "win32") : nodeTrustMessage(file.path);
5356
+ io.stderr.write(`${refuseAcl(acl.text, said)}\n`);
4922
5357
  return EX_CONFIG;
4923
5358
  }
4924
5359
  }
4925
5360
  }
4926
5361
  else {
5362
+ const acls = posixAclWriters(trustFiles.map((file) => file.path), trustPlat, exec);
4927
5363
  for (const file of trustFiles) {
5364
+ const said = isModuleSearchDir(file.path) ? moduleDirTrustMessage(file.path, trustPlat) : nodeTrustMessageFor(file.path, trustPlat);
4928
5365
  if (posixEntryUntrusted(file.path, file.ancestor)) {
4929
- io.stderr.write(`${nodeTrustMessageFor(file.path, trustPlat)}\n`);
5366
+ io.stderr.write(`${said}\n`);
5367
+ return EX_CONFIG;
5368
+ }
5369
+ const detail = posixAclWriterDetail(acls.has(file.path) ? acls.get(file.path) : "unreadable");
5370
+ if (detail) {
5371
+ io.stderr.write(`${said} (${detail})\n`);
4930
5372
  return EX_CONFIG;
4931
5373
  }
4932
5374
  }
@@ -5004,7 +5446,7 @@ async function runInstallBody(argv, hooks = {}) {
5004
5446
  const looked = exec(toolArgv("powershell", [
5005
5447
  "-NoProfile",
5006
5448
  "-Command",
5007
- `(Get-ItemProperty -Path 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\${sid}').ProfileImagePath`,
5449
+ profileImagePathCommand(sid),
5008
5450
  ], "win32"));
5009
5451
  // The agent token no longer lives in the profile (R14-8), so an unreadable
5010
5452
  // ProfileImagePath is not a refusal; a readable one that disagrees still is.
@@ -5199,7 +5641,7 @@ function windowsServiceSid(exec) {
5199
5641
  "-NoProfile",
5200
5642
  "-NonInteractive",
5201
5643
  "-Command",
5202
- "(Get-LocalUser -Name 'verax-svc').SID.Value",
5644
+ WINDOWS_SERVICE_SID_COMMAND,
5203
5645
  ], "win32"));
5204
5646
  if ((ran.status ?? 1) !== 0)
5205
5647
  return null;