@verax-ai/body 0.4.1 → 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/desktop.js CHANGED
@@ -5,9 +5,17 @@ import { createConnection, createServer } from "node:net";
5
5
  import { basename, dirname, join, parse, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { DESKTOP_PARENT_PID } from "./desktop-parent.js";
8
- import { defaultExec, foreignAclPrincipals, posixOthersCanReplace, readSddlBatch, restrictToOwnerWin32, sddlOwner, systemToolEnv, systemToolPath, toolArgv, windowsDirectorySids, windowsInvokingSid, windowsUserCanWrite, } from "./install.js";
8
+ import { defaultExec, foreignAclPrincipals, moduleSearchDirs, posixAclWriterDetail, posixAclWriters, posixOthersCanReplace, readSddlBatch, restrictToOwnerWin32, sddlOwner, systemToolEnv, systemToolPath, toolArgv, trustTargets, windowsDirectorySids, windowsInvokingSid, windowsUserCanWrite, } from "./install.js";
9
9
  import { hasRegisteredOperator } from "./operator-credentials.js";
10
10
  import { pidAlive, readLockFile } from "./unlock.js";
11
+ // With VERAX_DESKTOP_TRACE=1 each startup step writes one stderr line with the
12
+ // milliseconds since this module loaded. Windows CI has waited ~87 s before the
13
+ // issuer port opened; these lines say which step held it.
14
+ const traceZero = Date.now();
15
+ function trace(step) {
16
+ if (process.env.VERAX_DESKTOP_TRACE === "1")
17
+ process.stderr.write(`desktop-trace ${step} ${Date.now() - traceZero}ms\n`);
18
+ }
11
19
  /** One stderr line when this state has no enrolled operator. */
12
20
  export const DESKTOP_PASSKEY_HINT = "the panel reads the ledger after a passkey sign-in; run verax operator enroll\n";
13
21
  /**
@@ -114,12 +122,25 @@ export function parseDesktopArgs(argv, platform = process.platform) {
114
122
  }
115
123
  if (!stateDir)
116
124
  return { error: "usage" };
117
- if (platform === "win32" && desktopStateUncOrDevice(stateDir))
125
+ // Resolved against this process's cwd. The children start with cwd = repoRoot,
126
+ // so a relative --state or --inventory would otherwise be created somewhere
127
+ // other than the path this check judged. A relative name under a UNC cwd
128
+ // resolves onto that share, so the device check sees both strings.
129
+ const resolvedState = resolve(stateDir);
130
+ if (platform === "win32" && (desktopStateUncOrDevice(stateDir) || desktopStateUncOrDevice(resolvedState))) {
118
131
  return { error: "desktop-state-unc" };
132
+ }
119
133
  if (![panelPort, issuerPort, bodyPort].every((n) => Number.isInteger(n) && n > 0 && n < 65536)) {
120
134
  return { error: "port-invalid" };
121
135
  }
122
- return { stateDir, panelPort, issuerPort, bodyPort, browser, inventoryFile };
136
+ return {
137
+ stateDir: resolvedState,
138
+ panelPort,
139
+ issuerPort,
140
+ bodyPort,
141
+ browser,
142
+ inventoryFile: inventoryFile === undefined ? undefined : resolve(inventoryFile),
143
+ };
123
144
  }
124
145
  export function portOpen(port, host = "127.0.0.1") {
125
146
  return new Promise((resolve) => {
@@ -220,16 +241,33 @@ export function discardStaleFile(file) {
220
241
  throw err;
221
242
  }
222
243
  }
244
+ /** JWK members that carry private or symmetric key material. A pin is public verification material. */
245
+ const JWK_PRIVATE_FIELDS = new Set(["d", "p", "q", "dp", "dq", "qi", "k"]);
246
+ function jwkCarriesPrivateMaterial(key) {
247
+ if (key === null || typeof key !== "object")
248
+ return false;
249
+ return Object.keys(key).some((field) => JWK_PRIVATE_FIELDS.has(field));
250
+ }
223
251
  /**
224
252
  * The pin is the file the issuer just wrote. Compact JSON, or a throw when
225
- * it is not a key set. Nothing is fetched.
253
+ * it is not a key set. Nothing is fetched. A symlink for `dev-issuer` or for
254
+ * the pin file is refused, and so is any key that carries private material:
255
+ * those fail closed instead of being stripped out.
226
256
  */
227
257
  export function readIssuerJwksPin(stateDir) {
258
+ if (devIssuerIsLink(stateDir))
259
+ throw new Error("desktop-jwks-pin-failed");
260
+ const pinPath = issuerJwksPinPath(stateDir);
228
261
  let text;
229
262
  try {
230
- text = readFileSync(issuerJwksPinPath(stateDir), "utf8");
263
+ const st = lstatSync(pinPath);
264
+ if (st.isSymbolicLink() || !st.isFile())
265
+ throw new Error("desktop-jwks-pin-failed");
266
+ text = readFileSync(pinPath, "utf8");
231
267
  }
232
- catch {
268
+ catch (err) {
269
+ if (err instanceof Error && err.message === "desktop-jwks-pin-failed")
270
+ throw err;
233
271
  throw new Error("desktop-jwks-pin-failed");
234
272
  }
235
273
  try {
@@ -237,6 +275,8 @@ export function readIssuerJwksPin(stateDir) {
237
275
  if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.keys) || parsed.keys.length === 0) {
238
276
  throw new Error("desktop-jwks-pin-failed");
239
277
  }
278
+ if (parsed.keys.some((key) => jwkCarriesPrivateMaterial(key)))
279
+ throw new Error("desktop-jwks-pin-failed");
240
280
  return JSON.stringify({ keys: parsed.keys });
241
281
  }
242
282
  catch (err) {
@@ -422,6 +462,7 @@ function devIssuerIsLink(dir) {
422
462
  */
423
463
  function readWindowsAcls(paths) {
424
464
  const read = readSddlBatch(defaultExec, paths);
465
+ trace(`acl-read n=${paths.length}`);
425
466
  const out = new Map();
426
467
  for (const p of paths) {
427
468
  const hit = read.get(p);
@@ -437,17 +478,24 @@ function readWindowsAcls(paths) {
437
478
  return out;
438
479
  }
439
480
  let localAccounts = null;
481
+ /**
482
+ * Built-in Administrator (`LA`) and Guest (`LG`) via the SID constructor.
483
+ * The constructor lives in the runtime, so this command loads no module.
484
+ */
485
+ export const LOCAL_ACCOUNT_SIDS_COMMAND = "[Security.Principal.SecurityIdentifier]::new('LA').Value; [Security.Principal.SecurityIdentifier]::new('LG').Value";
440
486
  /** This machine's built-in Administrator and Guest SIDs, which an SDDL writes as `LA` and `LG`. Empty when the lookup fails. */
441
487
  function localAccountSids() {
442
488
  if (localAccounts)
443
489
  return localAccounts;
490
+ trace("local-account-sids-start");
444
491
  const ran = defaultExec(toolArgv("powershell", [
445
492
  "-NoProfile",
446
493
  "-NonInteractive",
447
494
  "-Command",
448
- "[Security.Principal.SecurityIdentifier]::new('LA').Value; [Security.Principal.SecurityIdentifier]::new('LG').Value",
495
+ LOCAL_ACCOUNT_SIDS_COMMAND,
449
496
  ], "win32"));
450
497
  const sids = (ran.status ?? 1) === 0 ? (ran.stdout ?? "").match(/S-1-5-21-[0-9-]+/g) ?? [] : [];
498
+ trace("local-account-sids");
451
499
  localAccounts = sids.length === 2 && sids[0].endsWith("-500") && sids[1].endsWith("-501") ? { LA: sids[0], LG: sids[1] } : {};
452
500
  return localAccounts;
453
501
  }
@@ -574,8 +622,9 @@ function intermediateLink(dir) {
574
622
  return dirname(abs);
575
623
  return null;
576
624
  }
577
- function refusePosixAncestors(dir) {
625
+ function refusePosixAncestors(dir, platform, pread) {
578
626
  const uid = typeof process.getuid === "function" ? process.getuid() : 0;
627
+ const present = [];
579
628
  for (const ancestor of ancestorPaths(dir)) {
580
629
  let st;
581
630
  try {
@@ -588,10 +637,23 @@ function refusePosixAncestors(dir) {
588
637
  }
589
638
  if (!st)
590
639
  continue;
591
- const ownerIsOperator = st.uid === 0 || st.uid === uid;
592
- if (posixOthersCanReplace({ uid: ownerIsOperator ? 0 : st.uid, mode: st.mode, symlink: st.isSymbolicLink() }, true)) {
593
- refuseDesktopDirectory(dir, `ancestor ${ancestor} can be replaced by another user`);
640
+ present.push({ path: ancestor, st });
641
+ }
642
+ const acls = pread ?? (present.length === 0
643
+ ? new Map()
644
+ : posixAclWriters(present.map((row) => row.path), platform, defaultExec));
645
+ for (const row of present) {
646
+ const ownerIsOperator = row.st.uid === 0 || row.st.uid === uid;
647
+ if (posixOthersCanReplace({ uid: ownerIsOperator ? 0 : row.st.uid, mode: row.st.mode, symlink: row.st.isSymbolicLink() }, true)) {
648
+ refuseDesktopDirectory(dir, `ancestor ${row.path} can be replaced by another user`);
649
+ }
650
+ const found = acls.has(row.path) ? acls.get(row.path) : "unreadable";
651
+ if (found === "unreadable") {
652
+ refuseDesktopDirectory(dir, `ancestor ${row.path} ACL could not be read (install acl or remove the ACL)`);
594
653
  }
654
+ const detail = posixAclWriterDetail(found);
655
+ if (detail)
656
+ refuseDesktopDirectory(dir, `ancestor ${row.path} can be replaced by another user (${detail})`);
595
657
  }
596
658
  }
597
659
  function ancestorInvokingSid(dir, opts) {
@@ -607,25 +669,48 @@ function ancestorInvokingSid(dir, opts) {
607
669
  return "";
608
670
  }
609
671
  }
610
- function refuseWindowsAncestors(dir, opts) {
672
+ /** Ancestors that exist. A missing ancestor is skipped; any other stat error is a refusal. */
673
+ function presentAncestors(dir) {
674
+ return ancestorPaths(dir).filter((ancestor) => {
675
+ try {
676
+ lstatSync(ancestor);
677
+ return true;
678
+ }
679
+ catch (err) {
680
+ if (err.code === "ENOENT")
681
+ return false;
682
+ return refuseDesktopDirectory(dir, `ancestor ${ancestor} could not be read`);
683
+ }
684
+ });
685
+ }
686
+ /**
687
+ * True when `dir` is already a real directory. A missing path, a link, or a
688
+ * non-directory stays on the caller's existing path, including a stat error
689
+ * that the later `lstat` still reports.
690
+ */
691
+ function isExistingRealDirectory(dir) {
692
+ try {
693
+ const st = lstatSync(dir);
694
+ return !st.isSymbolicLink() && st.isDirectory();
695
+ }
696
+ catch {
697
+ return false;
698
+ }
699
+ }
700
+ function refuseWindowsAncestors(dir, opts, preread) {
611
701
  if ((opts?.windowsDirectoryDacl || opts?.windowsDirectoryOwner) && !opts?.windowsAncestorDacl)
612
702
  return;
613
703
  const svc = ancestorInvokingSid(dir, opts);
704
+ trace("ancestors-invoking-sid");
614
705
  const ancestors = ancestorPaths(dir);
615
706
  let read = null;
616
- if (!opts?.windowsAncestorDacl) {
617
- const present = ancestors.filter((ancestor) => {
618
- try {
619
- lstatSync(ancestor);
620
- return true;
621
- }
622
- catch (err) {
623
- if (err.code === "ENOENT")
624
- return false;
625
- return refuseDesktopDirectory(dir, `ancestor ${ancestor} could not be read`);
626
- }
627
- });
707
+ if (preread) {
708
+ read = preread;
709
+ }
710
+ else if (!opts?.windowsAncestorDacl) {
711
+ const present = presentAncestors(dir);
628
712
  read = readWindowsAcls(present);
713
+ trace(`ancestors-acl-read n=${present.length}`);
629
714
  }
630
715
  for (const ancestor of ancestors) {
631
716
  let acl;
@@ -646,14 +731,22 @@ function refuseWindowsAncestors(dir, opts) {
646
731
  }
647
732
  }
648
733
  /** Intermediate link, or an ancestor another user can replace. Same rule for a new directory and an existing one. */
649
- function refuseDesktopAncestors(dir, platform, opts) {
734
+ function refuseDesktopAncestors(dir, platform, opts, preread, posixAcl) {
650
735
  const link = intermediateLink(dir);
651
736
  if (link)
652
737
  refuseDesktopDirectory(dir, `ancestor ${link} is a link`);
653
738
  if (platform === "win32")
654
- refuseWindowsAncestors(dir, opts);
739
+ refuseWindowsAncestors(dir, opts, preread);
655
740
  else
656
- refusePosixAncestors(dir);
741
+ refusePosixAncestors(dir, platform, posixAcl);
742
+ }
743
+ function refusePosixLeafAcl(dir, found) {
744
+ if (found === "unreadable") {
745
+ refuseDesktopDirectory(dir, "the directory ACL could not be read (install acl or remove the ACL)");
746
+ }
747
+ const detail = posixAclWriterDetail(found);
748
+ if (detail)
749
+ refuseDesktopDirectory(dir, `${DIRECTORY_WRITABLE_BY_OTHERS} (${detail})`);
657
750
  }
658
751
  /**
659
752
  * Create `dir` as mode 0700. An existing directory another user could write
@@ -666,11 +759,35 @@ function refuseDesktopAncestors(dir, platform, opts) {
666
759
  * refused. On Windows an existing directory is refused unless its owner SID
667
760
  * is the invoking SID, Administrators, or SYSTEM. An ancestor another user
668
761
  * can replace, or an intermediate link, is refused the same way for a new
669
- * directory and for one that already exists.
762
+ * directory and for one that already exists. On POSIX an extended ACL that
763
+ * grants a write right, or an ACL that cannot be read, is refused the same
764
+ * way once the mode bits themselves are safe. chmod does not remove a macOS ACL.
670
765
  */
671
766
  function ensureDesktopDirectory(dir, restrict, opts) {
672
767
  const platform = opts?.platform ?? process.platform;
673
- refuseDesktopAncestors(dir, platform, opts);
768
+ trace(`dir-start ${basename(dir)}`);
769
+ // An existing directory and the ancestors that already exist share one SDDL
770
+ // read. A path that is not there yet still reads ancestors before mkdir and
771
+ // again after mkdir, so a directory created in between is not missed.
772
+ // Hooked owner and DACL lookups stay on their own calls.
773
+ const noWindowsAclHooks = !opts?.windowsDirectoryOwner && !opts?.windowsDirectoryDacl && !opts?.windowsAncestorDacl;
774
+ let preread;
775
+ if (platform === "win32" && noWindowsAclHooks && isExistingRealDirectory(dir)) {
776
+ const link = intermediateLink(dir);
777
+ if (link)
778
+ refuseDesktopDirectory(dir, `ancestor ${link} is a link`);
779
+ preread = readWindowsAcls([...presentAncestors(dir), dir]);
780
+ }
781
+ // One POSIX ACL read for the ancestors and, when it already exists, the directory.
782
+ let posixAcl;
783
+ if (platform !== "win32") {
784
+ const aclPaths = presentAncestors(dir);
785
+ if (isExistingRealDirectory(dir))
786
+ aclPaths.push(dir);
787
+ posixAcl = aclPaths.length === 0 ? new Map() : posixAclWriters(aclPaths, platform, defaultExec);
788
+ }
789
+ refuseDesktopAncestors(dir, platform, opts, preread, posixAcl);
790
+ trace("dir-ancestors");
674
791
  let existing = null;
675
792
  try {
676
793
  existing = lstatSync(dir);
@@ -685,7 +802,12 @@ function ensureDesktopDirectory(dir, restrict, opts) {
685
802
  if (platform === "win32") {
686
803
  // Production passes no hook: owner and DACL come from one SDDL read.
687
804
  const daclHook = opts?.windowsDirectoryDacl;
688
- const leaf = !opts?.windowsDirectoryOwner && !daclHook ? readWindowsAcls([dir]).get(dir) : undefined;
805
+ const leaf = preread
806
+ ? preread.get(dir)
807
+ : !opts?.windowsDirectoryOwner && !daclHook
808
+ ? readWindowsAcls([dir]).get(dir)
809
+ : undefined;
810
+ trace("dir-leaf-acl");
689
811
  if (leaf && leaf.sddl === null) {
690
812
  refuseDesktopDirectory(dir, `the directory ACL could not be read${unreadable(leaf.why)}; use a new directory`);
691
813
  }
@@ -694,6 +816,7 @@ function ensureDesktopDirectory(dir, restrict, opts) {
694
816
  if (leaf?.sddl) {
695
817
  owner = sddlOwner(leaf.sddl)?.toUpperCase() ?? "";
696
818
  invoking = windowsInvokingSid()?.trim().toUpperCase() ?? "";
819
+ trace("dir-invoking-sid");
697
820
  }
698
821
  else {
699
822
  const found = (opts?.windowsDirectoryOwner ?? windowsDirectorySids)(dir);
@@ -719,6 +842,7 @@ function ensureDesktopDirectory(dir, restrict, opts) {
719
842
  refuseDesktopDirectory(dir, "dev-issuer in that directory is a symlink or junction; use a new directory");
720
843
  }
721
844
  restrict(dir);
845
+ trace("dir-restrict");
722
846
  return;
723
847
  }
724
848
  const uid = typeof process.getuid === "function" ? process.getuid() : existing.uid;
@@ -726,6 +850,7 @@ function ensureDesktopDirectory(dir, restrict, opts) {
726
850
  refuseDesktopDirectory(dir);
727
851
  if ((existing.mode & 0o022) !== 0)
728
852
  refuseDesktopDirectory(dir, DIRECTORY_WRITABLE_BY_OTHERS);
853
+ refusePosixLeafAcl(dir, posixAcl && posixAcl.has(dir) ? posixAcl.get(dir) : "unreadable");
729
854
  if (devIssuerIsLink(dir)) {
730
855
  refuseDesktopDirectory(dir, "dev-issuer in that directory is a symlink or junction; use a new directory");
731
856
  }
@@ -735,17 +860,29 @@ function ensureDesktopDirectory(dir, restrict, opts) {
735
860
  }
736
861
  mkdirSync(dir, { recursive: true, mode: 0o700 });
737
862
  // A missing intermediate directory another user created between the first check and mkdir is theirs now.
738
- refuseDesktopAncestors(dir, platform, opts);
863
+ let createdAcl;
864
+ if (platform === "win32") {
865
+ refuseDesktopAncestors(dir, platform, opts);
866
+ }
867
+ else {
868
+ const createdPaths = [...presentAncestors(dir), dir];
869
+ const again = posixAclWriters(createdPaths, platform, defaultExec);
870
+ refuseDesktopAncestors(dir, platform, opts, undefined, again);
871
+ createdAcl = again.has(dir) ? again.get(dir) : "unreadable";
872
+ }
873
+ trace("dir-ancestors-after-mkdir");
739
874
  const created = lstatSync(dir);
740
875
  if (created.isSymbolicLink() || !created.isDirectory())
741
876
  refuseDesktopDirectory(dir);
742
877
  if (platform === "win32") {
743
878
  restrict(dir);
879
+ trace("dir-restrict");
744
880
  return;
745
881
  }
746
882
  const uid = typeof process.getuid === "function" ? process.getuid() : created.uid;
747
883
  if (created.uid !== uid)
748
884
  refuseDesktopDirectory(dir);
885
+ refusePosixLeafAcl(dir, createdAcl);
749
886
  chmodSync(dir, 0o700);
750
887
  }
751
888
  /** Synchronous: `spawnSync` on Windows, `process.kill` elsewhere. An `exit` handler can call it. */
@@ -803,11 +940,46 @@ export function issuerEnv(base, opts, audience, issuerUrl) {
803
940
  VERAX_RP_ORIGINS: keptOr(base, "VERAX_RP_ORIGINS", issuerUrl),
804
941
  };
805
942
  }
806
- function cleanEnv() {
807
- const env = { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" };
808
- delete env.VERAX_DEV_TOKEN;
943
+ /**
944
+ * The approval ceremony runs on the panel page, so the body names that
945
+ * origin. An operator who already set either value keeps it. This does not
946
+ * touch the issuer: `/authorize` and `/enroll` still use `issuerEnv`.
947
+ */
948
+ export function bodyRpEnv(base, panelOrigin) {
949
+ return {
950
+ VERAX_RP_ID: keptOr(base, "VERAX_RP_ID", "localhost"),
951
+ VERAX_RP_ORIGINS: keptOr(base, "VERAX_RP_ORIGINS", panelOrigin),
952
+ };
953
+ }
954
+ /** Removed from every child. Compared case-insensitively: on Windows `node_options` is `NODE_OPTIONS`. */
955
+ const DESKTOP_CHILD_ENV_DROPPED = new Set([
956
+ "NODE_OPTIONS",
957
+ "NODE_PATH",
958
+ "NODE_REPL_EXTERNAL_MODULE",
959
+ "LD_PRELOAD",
960
+ "LD_LIBRARY_PATH",
961
+ // glibc loads an audit library named here into the child, like LD_PRELOAD.
962
+ "LD_AUDIT",
963
+ "DYLD_INSERT_LIBRARIES",
964
+ "DYLD_LIBRARY_PATH",
965
+ "VERAX_DEV_TOKEN",
966
+ ]);
967
+ /**
968
+ * Environment handed to a desktop child. Bootstrap and preload variables are
969
+ * removed. Other `VERAX_*` names are left as given. `NO_COLOR` and `FORCE_COLOR`
970
+ * stay forced off, as they were before this filter.
971
+ */
972
+ export function desktopChildEnv(base) {
973
+ const env = { ...base, NO_COLOR: "1", FORCE_COLOR: "0" };
974
+ for (const key of Object.keys(env)) {
975
+ if (DESKTOP_CHILD_ENV_DROPPED.has(key.toUpperCase()))
976
+ delete env[key];
977
+ }
809
978
  return env;
810
979
  }
980
+ function cleanEnv() {
981
+ return desktopChildEnv(process.env);
982
+ }
811
983
  /**
812
984
  * `windowsHide` is right for the servers: it keeps a console window off the
813
985
  * screen. It is wrong for the browser. On Windows the flag becomes SW_HIDE in
@@ -843,6 +1015,111 @@ function defaultBrowser() {
843
1015
  return p;
844
1016
  return null;
845
1017
  }
1018
+ function codeInstallPlatform(platform) {
1019
+ if (platform === "win32" || platform === "darwin")
1020
+ return platform;
1021
+ return "linux";
1022
+ }
1023
+ /**
1024
+ * Code the desktop launches, the directory that holds each file, and every
1025
+ * `node_modules` Node would search from there. `trustTargets` marks the
1026
+ * parent of a script as an ancestor; only a Windows executable's parent is
1027
+ * an object there. Adding a file next to the script is the same threat, so
1028
+ * the file and its parent are objects here and only the directories above
1029
+ * them stay ancestors. A path that is both is kept once, as an object.
1030
+ */
1031
+ function desktopCodeTargets(files, platform) {
1032
+ const merged = new Map();
1033
+ const put = (file, ancestor) => {
1034
+ const key = platform === "win32" ? file.toLowerCase() : file;
1035
+ const prev = merged.get(key);
1036
+ if (!prev) {
1037
+ merged.set(key, { path: file, ancestor });
1038
+ return;
1039
+ }
1040
+ if (prev.ancestor && !ancestor)
1041
+ merged.set(key, { path: prev.path, ancestor: false });
1042
+ };
1043
+ for (const file of files) {
1044
+ const chain = trustTargets(file, platform);
1045
+ for (let i = 0; i < chain.length; i += 1)
1046
+ put(chain[i].path, i > 1);
1047
+ for (const dir of moduleSearchDirs(dirname(file), platform))
1048
+ put(dir, false);
1049
+ }
1050
+ return [...merged.values()];
1051
+ }
1052
+ function inspectCodePath(file) {
1053
+ try {
1054
+ const st = lstatSync(file);
1055
+ if (st.isSymbolicLink() || (!st.isDirectory() && !st.isFile())) {
1056
+ return { ok: false, detail: " (is a link or not a regular file)" };
1057
+ }
1058
+ return { ok: true, uid: st.uid, mode: st.mode };
1059
+ }
1060
+ catch {
1061
+ return { ok: false, detail: " (could not be read)" };
1062
+ }
1063
+ }
1064
+ /** Third line of a code refusal: what the operator can do about this checkout. */
1065
+ function desktopCodeFix(platform, repoRoot) {
1066
+ if (platform === "win32") {
1067
+ return `fix: clone under your user profile, or run: icacls "${repoRoot}" /inheritance:r /grant:r "%USERNAME%:(OI)(CI)F" "*S-1-5-18:(OI)(CI)F" "*S-1-5-32-544:(OI)(CI)F"`;
1068
+ }
1069
+ return `fix: chmod -R go-w "${repoRoot}" and make sure every parent directory is owned by you or root`;
1070
+ }
1071
+ /**
1072
+ * First launched script, parent, ancestor, or module directory that someone
1073
+ * else can replace. Null when every target is held tightly enough to run.
1074
+ * `detail` is the second line of the refusal. On Windows one `read` (or
1075
+ * `readWindowsAcls`) judges the whole list with `svcSid`: someone other than
1076
+ * the operator, Administrators, or SYSTEM. On POSIX the owner is trusted
1077
+ * when it is the operator or root, then `posixOthersCanReplace`, then one
1078
+ * `posixAclWriters` read of the whole list.
1079
+ */
1080
+ export function desktopCodeRefusal(paths, platform, read, invoking) {
1081
+ const targets = desktopCodeTargets(paths, codeInstallPlatform(platform));
1082
+ const wanted = targets.map((target) => target.path);
1083
+ const acls = platform === "win32" ? (read !== undefined ? read(wanted) : readWindowsAcls(wanted)) : null;
1084
+ const posixAcl = platform === "win32"
1085
+ ? null
1086
+ : posixAclWriters(wanted, platform === "darwin" ? "darwin" : "linux", defaultExec);
1087
+ const svc = invoking?.trim().toUpperCase() ?? "";
1088
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
1089
+ for (const target of targets) {
1090
+ const inspected = inspectCodePath(target.path);
1091
+ if (!inspected.ok)
1092
+ return { path: target.path, detail: inspected.detail };
1093
+ if (platform === "win32") {
1094
+ const sddl = acls?.get(target.path)?.sddl ?? null;
1095
+ if (sddl === null)
1096
+ return { path: target.path, detail: " (ACL could not be read)" };
1097
+ if (windowsUserCanWrite(sddl, { path: target.path, svcSid: svc, ancestor: target.ancestor })) {
1098
+ return { path: target.path, detail: aclWho(sddl, svc) };
1099
+ }
1100
+ continue;
1101
+ }
1102
+ const ownerIsOperator = inspected.uid === 0 || inspected.uid === uid;
1103
+ if (posixOthersCanReplace({ uid: ownerIsOperator ? 0 : inspected.uid, mode: inspected.mode, symlink: false }, target.ancestor)) {
1104
+ return {
1105
+ path: target.path,
1106
+ detail: ` (owner uid ${inspected.uid}; mode ${(inspected.mode & 0o777).toString(8)})`,
1107
+ };
1108
+ }
1109
+ const found = posixAcl && posixAcl.has(target.path) ? posixAcl.get(target.path) : "unreadable";
1110
+ const writers = posixAclWriterDetail(found);
1111
+ if (writers)
1112
+ return { path: target.path, detail: ` (${writers})` };
1113
+ }
1114
+ return null;
1115
+ }
1116
+ function codeInvoking(platform, stateDir, hooks) {
1117
+ if (platform !== "win32")
1118
+ return undefined;
1119
+ if (hooks?.windowsDirectoryOwner)
1120
+ return hooks.windowsDirectoryOwner(stateDir).invokingSid?.trim().toUpperCase() ?? "";
1121
+ return windowsInvokingSid()?.trim().toUpperCase() ?? "";
1122
+ }
846
1123
  export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s), hooks) {
847
1124
  const repoRoot = resolveRepoRoot();
848
1125
  const cloneOnly = desktopCloneError(repoRoot);
@@ -976,7 +1253,23 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
976
1253
  windowsDirectoryDacl: hooks?.windowsDirectoryDacl,
977
1254
  windowsAncestorDacl: hooks?.windowsAncestorDacl,
978
1255
  });
1256
+ // A spawn hook stands in for the children, so those tests never execute these
1257
+ // files and skip this check. `windowsCodeAcl` is the test that wants the
1258
+ // refusal, including its fix line, and it runs even when spawn is set.
1259
+ // Production, which has no spawn hook, always runs it.
1260
+ if (!hooks?.spawn || hooks.windowsCodeAcl) {
1261
+ const codeFiles = [issuerScript, mainTs, viteJs];
1262
+ const codePlatform = hooks?.platform ?? process.platform;
1263
+ const invoking = codeInvoking(codePlatform, opts.stateDir, hooks);
1264
+ const refused = desktopCodeRefusal(codeFiles, codePlatform, hooks?.windowsCodeAcl, invoking);
1265
+ if (refused !== null) {
1266
+ writeErr(`desktop-code-writable:${refused.path}\n${refused.detail.trim()}\n${desktopCodeFix(codePlatform, repoRoot)}\n`);
1267
+ stopAll();
1268
+ return 1;
1269
+ }
1270
+ }
979
1271
  const decided = await desktopMode(opts.stateDir, opts.bodyPort, hooks?.listenerPid);
1272
+ trace("mode-decided");
980
1273
  if ("error" in decided) {
981
1274
  const named = decided.lockPort === null ? "unknown" : String(decided.lockPort);
982
1275
  writeErr(`${decided.error}:${decided.pid}:${named}\n`);
@@ -1009,12 +1302,14 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
1009
1302
  discardStaleFile(issuerJwksPinPath(opts.stateDir));
1010
1303
  if (await busy("issuer", opts.issuerPort))
1011
1304
  return 1;
1305
+ trace("issuer-launch");
1012
1306
  const issuer = launch("issuer", process.execPath, ["--experimental-strip-types", issuerScript, "--out", tokenPath], { ...issuerEnv(cleanEnv(), opts, audience, issuerUrl), [DESKTOP_PARENT_PID]: String(process.pid) }, repoRoot);
1013
1307
  kids.push(issuer);
1014
1308
  arm("issuer", issuer);
1015
1309
  const issuerOut = { text: "" };
1016
1310
  pipe("issuer", issuer, issuerOut);
1017
1311
  const issuerReady = await waitReady(issuer, issuerOut, (text) => text.includes(issuerReadyLine(opts.issuerPort)), hooks?.readyMs ?? 15_000);
1312
+ trace(`issuer-${issuerReady}`);
1018
1313
  if (issuerReady === "exited")
1019
1314
  return childFailed("issuer");
1020
1315
  if (issuerReady === "timeout") {
@@ -1052,8 +1347,10 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
1052
1347
  }
1053
1348
  if (await busy("body", opts.bodyPort))
1054
1349
  return 1;
1350
+ trace("body-launch");
1055
1351
  const body = launch("body", process.execPath, ["--experimental-strip-types", mainTs], {
1056
1352
  ...cleanEnv(),
1353
+ ...bodyRpEnv(cleanEnv(), panelOrigin),
1057
1354
  VERAX_STATE_DIR: opts.stateDir,
1058
1355
  VERAX_ISSUER: issuerUrl,
1059
1356
  VERAX_JWKS_URL: `${issuerLoopback}/.well-known/jwks.json`,
@@ -1070,6 +1367,7 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
1070
1367
  const bodyOut = { text: "" };
1071
1368
  pipe("body", body, bodyOut);
1072
1369
  const bodyReady = await waitReady(body, bodyOut, (text) => text.includes(bodyReadyLine(opts.bodyPort)), hooks?.readyMs ?? 15_000);
1370
+ trace(`body-${bodyReady}`);
1073
1371
  if (bodyReady === "exited")
1074
1372
  return childFailed("body");
1075
1373
  if (bodyReady === "timeout") {
@@ -1084,6 +1382,7 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
1084
1382
  join(repoRoot, "packages"),
1085
1383
  ];
1086
1384
  if (!hooks?.spawn && panelBuildNeeded(join(panelDir, "dist", "index.html"), panelSources)) {
1385
+ trace("panel-build");
1087
1386
  const built = spawnSync(process.execPath, [viteJs, "build"], {
1088
1387
  cwd: panelDir,
1089
1388
  env: { ...cleanEnv(), VERAX_BODY_URL: bodyLoopback },
@@ -1111,6 +1410,7 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
1111
1410
  const panelOut = { text: "" };
1112
1411
  pipe("panel", panel, panelOut);
1113
1412
  const panelReady = await waitReady(panel, panelOut, (text) => text.includes(panelReadyLine(opts.panelPort)), hooks?.readyMs ?? 20_000);
1413
+ trace(`panel-${panelReady}`);
1114
1414
  if (panelReady === "exited")
1115
1415
  return childFailed("panel");
1116
1416
  if (panelReady === "timeout") {
@@ -1142,6 +1442,7 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
1142
1442
  `--app=${url}`,
1143
1443
  "--window-size=1360,880",
1144
1444
  ];
1445
+ trace("browser-launch");
1145
1446
  const browser = launch("browser", browserBin, browserArgv, cleanEnv(), repoRoot, false);
1146
1447
  kids.push(browser);
1147
1448
  pipe("browser", browser, { text: "" });
package/dist/halt.d.ts CHANGED
@@ -4,8 +4,13 @@
4
4
  * `halt-history.jsonl` beside it, one line per halt or resume, so the panel
5
5
  * can say "stopped by operator-7 at 14:02" and a resume is not silent.
6
6
  *
7
- * The history is a plain append-only file, not a signed ledger record. The
8
- * calls refused while halted are signed; the switch itself is not.
7
+ * The history file itself stays plain text. Each line is copied into the
8
+ * ledger as a signed control record (subject `verax.halt` or `verax.resume`)
9
+ * when the body opens, when `POST /api/halt` or `POST /api/resume` returns,
10
+ * or on the next call. A CLI halt is not in the ledger until one of those,
11
+ * and that delay is part of the record rather than something the file hides.
12
+ * Calls refused while halted are signed deny records, and they come after
13
+ * the halt control record in the chain.
9
14
  */
10
15
  export type HaltEvent = {
11
16
  action: "halt" | "resume";