@verax-ai/body 0.1.0 → 0.1.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/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to
46
+ the interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of,
58
+ the Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as
159
+ a result of this License or out of the use or inability to use
160
+ the Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ Copyright 2026 VERAX TEKNOLOJİ LİMİTED ŞİRKETİ
181
+
182
+ Licensed under the Apache License, Version 2.0 (the "License");
183
+ you may not use this file except in compliance with the License.
184
+ You may obtain a copy of the License at
185
+
186
+ http://www.apache.org/licenses/LICENSE-2.0
187
+
188
+ Unless required by applicable law or agreed to in writing, software
189
+ distributed under the License is distributed on an "AS IS" BASIS,
190
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
191
+ See the License for the specific language governing permissions and
192
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @verax-ai/body
2
+
3
+ The body an agent asks before it acts. An MCP server that puts every tool
4
+ call through a policy gate, writes a signed decision record before anything
5
+ runs, and keeps that ledger on the machine it runs on. A refusal is recorded
6
+ the same way as an approval.
7
+
8
+ Part of [Verax](https://github.com/verax-ai/verax) by
9
+ [VERAX Teknoloji](https://verax-ai.com). What the code carries and what stays
10
+ unproven is stated in
11
+ [`docs/STATUS.md`](https://github.com/verax-ai/verax/blob/main/docs/STATUS.md);
12
+ nothing here is a claim beyond that file.
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ npm install -g @verax-ai/body
18
+ verax --help
19
+ ```
20
+
21
+ Node 22.6 or newer. `@verax-ai/proxy` and `@verax-ai/inventory` install with it.
22
+
23
+ ## Configure
24
+
25
+ The body opens only when its authorization is configured; there is no default
26
+ token. It speaks MCP over Streamable HTTP at `/mcp` and refuses a call whose
27
+ Bearer token the configured issuer did not sign.
28
+
29
+ | Variable | Required | Meaning |
30
+ | --- | --- | --- |
31
+ | `VERAX_ISSUER` | yes | Issuer the agent's token must carry. |
32
+ | `VERAX_JWKS_URL` | yes | Where the body fetches the keys that verify that token. |
33
+ | `VERAX_AUDIENCE` | yes | Audience the token must name, so a token minted for something else is refused. |
34
+ | `VERAX_STATE_DIR` | yes | Directory the ledger, keys and approvals live in. It stays on this machine. |
35
+ | `VERAX_POLICY_FILE` | yes | Policy the gate applies. `@verax-ai/proxy` ships `policy/default.json`, which denies what it does not name. |
36
+ | `VERAX_BIND` | no | `host:port` to listen on. Default `127.0.0.1:8787`; anything but loopback needs `VERAX_TLS_TERMINATED=1`. |
37
+ | `VERAX_INVENTORY_FILE` | no | Roster document the body serves. The format is `@verax-ai/inventory`. |
38
+
39
+ `verax doctor` names what is missing. A misconfigured body exits with code 78
40
+ before it listens.
41
+
42
+ ## Run
43
+
44
+ ```sh
45
+ verax # serve MCP at http://127.0.0.1:8787/mcp
46
+ verax doctor # check the configuration this process would run with
47
+ ```
48
+
49
+ Point an MCP client at `http://127.0.0.1:8787/mcp` with a Bearer token from
50
+ your issuer. The tools the body offers are `memory.get`, `memory.put`,
51
+ `audit.explain`, `message.read`, `message.send` and `spend`. The policy
52
+ decides which of them a token's scopes may call, and a call can be held
53
+ until an operator on this machine approves it.
54
+
55
+ Other commands: `approve`, `operator`, `reconcile`, `witness`, `halt`,
56
+ `unlock`, `desktop`. `verax --help` lists them.
57
+
58
+ ## License
59
+
60
+ Apache-2.0.
@@ -0,0 +1,33 @@
1
+ import { type FileLedger } from "@verax-ai/proxy";
2
+ export type AgentRow = {
3
+ brain: string;
4
+ decisions: number;
5
+ allowed: number;
6
+ denied: number;
7
+ deferred: number;
8
+ /** Approvals waiting on an operator now, whatever the window. */
9
+ pending: number;
10
+ /** The newest decision in the window, or null when there was none. */
11
+ lastMs: number | null;
12
+ /** What the roster declares; null for an agent the roster does not name. */
13
+ roster: {
14
+ state: string;
15
+ label: string;
16
+ group: string | null;
17
+ } | null;
18
+ };
19
+ export type AgentsAnswer = {
20
+ fromMs: number;
21
+ toMs: number;
22
+ /** Pending first, then the most recently active; ties by name. */
23
+ agents: AgentRow[];
24
+ /** Decisions in the window whose inputs document was not found or did not match its hash. */
25
+ unattributed: number;
26
+ };
27
+ export declare function agentsWindow(opts: {
28
+ ledger: FileLedger;
29
+ stateDir: string;
30
+ inventoryFile: string | null | undefined;
31
+ fromMs: number;
32
+ toMs: number;
33
+ }): Promise<AgentsAnswer>;
package/dist/agents.js ADDED
@@ -0,0 +1,59 @@
1
+ // One row per agent for the panel's status tab: what each did in a window
2
+ // of the ledger, what is waiting on an operator for it, when it last acted,
3
+ // and what the roster says about it. A company runs hundreds of agents; the
4
+ // operator reads this list, not the records. The window is read from the
5
+ // end of the ledger, so the answer costs the window and not the ledger.
6
+ import { parseInventory } from "@verax-ai/inventory";
7
+ import { loadApprovalsFromDir } from "@verax-ai/proxy";
8
+ import { matchingInputs } from "./inputs-read.js";
9
+ import { readInventoryFile } from "./inventory-file.js";
10
+ export async function agentsWindow(opts) {
11
+ const { rows } = await opts.ledger.decisionsWindow(opts.fromMs, opts.toMs);
12
+ const inputs = (await matchingInputs(opts.stateDir, rows));
13
+ const byBrain = new Map();
14
+ const rowFor = (brain) => {
15
+ let row = byBrain.get(brain);
16
+ if (!row) {
17
+ row = { brain, decisions: 0, allowed: 0, denied: 0, deferred: 0, pending: 0, lastMs: null, roster: null };
18
+ byBrain.set(brain, row);
19
+ }
20
+ return row;
21
+ };
22
+ let unattributed = 0;
23
+ for (const d of rows) {
24
+ const ref = d.claims.ref;
25
+ const brain = typeof ref === "string" ? inputs[ref]?.principal?.brain : undefined;
26
+ if (typeof brain !== "string" || brain === "") {
27
+ unattributed += 1;
28
+ continue;
29
+ }
30
+ const row = rowFor(brain);
31
+ row.decisions += 1;
32
+ if (d.claims.decision === "allow")
33
+ row.allowed += 1;
34
+ else if (d.claims.decision === "deny")
35
+ row.denied += 1;
36
+ else if (d.claims.decision === "defer")
37
+ row.deferred += 1;
38
+ if (row.lastMs === null || d.claims.timestampMs > row.lastMs)
39
+ row.lastMs = d.claims.timestampMs;
40
+ }
41
+ for (const approval of loadApprovalsFromDir(opts.stateDir)) {
42
+ if (approval.status === "pending")
43
+ rowFor(approval.brain).pending += 1;
44
+ }
45
+ const door = readInventoryFile(opts.inventoryFile);
46
+ const parsed = door.inventory == null ? null : parseInventory(door.inventory);
47
+ if (parsed && parsed.ok) {
48
+ const groups = new Map(parsed.value.groups.map((g) => [g.id, g.label]));
49
+ for (const agent of parsed.value.agents) {
50
+ rowFor(agent.id).roster = {
51
+ state: agent.state,
52
+ label: agent.label,
53
+ group: agent.groupId === null ? null : (groups.get(agent.groupId) ?? agent.groupId),
54
+ };
55
+ }
56
+ }
57
+ const agents = [...byBrain.values()].sort((a, b) => b.pending - a.pending || (b.lastMs ?? -1) - (a.lastMs ?? -1) || a.brain.localeCompare(b.brain));
58
+ return { fromMs: opts.fromMs, toMs: opts.toMs, agents, unattributed };
59
+ }
@@ -1,6 +1,28 @@
1
+ import { existsSync, readFileSync } from "node:fs";
1
2
  import { userInfo } from "node:os";
2
- import { approvePending, approvalsLogFor, enqueueApprovalCommand, FileLedger, loadApprovalsFromDir } from "@verax-ai/proxy";
3
+ import { join } from "node:path";
4
+ import { approvePending, approvalsLogFor, createApprovalBudgetGuard, enqueueApprovalCommand, FileLedger, loadApprovalsFromDir, loadPolicy, } from "@verax-ai/proxy";
3
5
  import { loadOrCreateSigners } from "./keys.js";
6
+ function policyForApprove(stateDir, policyHash) {
7
+ const fromEnv = process.env.VERAX_POLICY_FILE?.trim();
8
+ if (fromEnv) {
9
+ try {
10
+ return loadPolicy(readFileSync(fromEnv, "utf8"));
11
+ }
12
+ catch {
13
+ // Fall through to the snapshot the body wrote for this hash.
14
+ }
15
+ }
16
+ const snap = join(stateDir, "policies", `${policyHash}.json`);
17
+ if (!existsSync(snap))
18
+ return null;
19
+ try {
20
+ return loadPolicy(JSON.parse(readFileSync(snap, "utf8")));
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
4
26
  function operatorName() {
5
27
  try {
6
28
  const name = userInfo().username;
@@ -65,6 +87,7 @@ export async function runApprove(argv, writeErr = (s) => process.stderr.write(s)
65
87
  writeErr("approve-unknown-ref\n");
66
88
  return 78;
67
89
  }
90
+ const policy = policyForApprove(stateDir, defer.claims.policyHash);
68
91
  const result = await approvePending({
69
92
  ledger,
70
93
  recordSigner: signers.recordSigner,
@@ -75,6 +98,9 @@ export async function runApprove(argv, writeErr = (s) => process.stderr.write(s)
75
98
  via: "cli",
76
99
  policyHash: defer.claims.policyHash,
77
100
  approvals,
101
+ ...(policy
102
+ ? { budgetGuard: createApprovalBudgetGuard({ policy, approvals, now: () => Date.now() }) }
103
+ : {}),
78
104
  });
79
105
  if (!result.ok) {
80
106
  writeErr(`approve-${result.reason}\n`);
package/dist/cli.js CHANGED
@@ -15,7 +15,7 @@ const HELP = `verax - the body an agent asks before it acts, and the ledger it a
15
15
 
16
16
  Usage: verax <command> [options]
17
17
 
18
- (no command) serve the body over MCP stdio, or HTTP when VERAX_PORT is set
18
+ (no command) serve MCP over Streamable HTTP at /mcp on VERAX_BIND (default 127.0.0.1:8787)
19
19
  doctor [--json] check the configuration this process would run with
20
20
  approve <args> approve a waiting request from this machine
21
21
  operator <args> enrol an operator and manage their passkeys
@@ -23,13 +23,14 @@ Usage: verax <command> [options]
23
23
  witness <stateDir> run the witness alongside a body
24
24
  halt <stateDir> stop the body from allowing anything further
25
25
  unlock [--force] <stateDir> clear a stale ledger lock
26
- desktop <args> open the local panel
26
+ desktop <args> open the local panel, joining the body that holds the ledger if one is up
27
27
 
28
28
  --help, -h print this
29
29
  --version, -v print the version
30
30
 
31
- Serving needs VERAX_ISSUER, VERAX_JWKS_URL and VERAX_AUDIENCE; \`verax doctor\`
32
- names what is missing. Records stay on this machine, under VERAX_STATE_DIR.
31
+ Serving needs VERAX_ISSUER, VERAX_JWKS_URL, VERAX_AUDIENCE, VERAX_STATE_DIR and
32
+ VERAX_POLICY_FILE; \`verax doctor\` names what is missing. Records stay on this
33
+ machine, under VERAX_STATE_DIR.
33
34
  `;
34
35
  function version() {
35
36
  // The published package answers with its own version, not a copy of it.
package/dist/desktop.d.ts CHANGED
@@ -17,6 +17,29 @@ export declare function parseDesktopArgs(argv: string[]): DesktopOpts | {
17
17
  error: string;
18
18
  };
19
19
  export declare function portOpen(port: number, host?: string): Promise<boolean>;
20
+ /** GET /healthz on the loopback port; true only for a 200. */
21
+ export declare function healthzUp(port: number): Promise<boolean>;
22
+ export type DesktopMode = {
23
+ mode: "spawn";
24
+ } | {
25
+ mode: "attach";
26
+ pid: number;
27
+ } | {
28
+ error: "desktop-body-locked";
29
+ pid: number;
30
+ };
31
+ /**
32
+ * One ledger, one body. The desktop used to build its own issuer and body on
33
+ * every open, which on a machine whose body starts at logon put the window on
34
+ * a second, empty ledger: the panel looked broken while the real decisions sat
35
+ * in the directory the lock names. So the lock is read first. Held by a live
36
+ * process that answers /healthz where this run was told to look, the panel
37
+ * joins that body. Held by a live process that does not answer there, the
38
+ * desktop stops: someone owns the ledger and is not where we were pointed, and
39
+ * a second body would be refused by the lock anyway. A dead or unreadable lock
40
+ * is the body's own to clear (`verax unlock`); the desktop builds as before.
41
+ */
42
+ export declare function desktopMode(stateDir: string, bodyPort: number, probe?: (port: number) => Promise<boolean>): Promise<DesktopMode>;
20
43
  export declare function killTree(pid: number | undefined): void;
21
44
  /** The panel's redirect is its own origin, so the issuer has to be told which port
22
45
  * this run put it on: the allow-list default only holds 5173 and 4173. */
package/dist/desktop.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { get } from "node:http";
3
4
  import { createConnection } from "node:net";
4
5
  import { dirname, join } from "node:path";
5
6
  import { fileURLToPath } from "node:url";
7
+ import { pidAlive, readLockFile } from "./unlock.js";
6
8
  const here = dirname(fileURLToPath(import.meta.url));
7
9
  const repoRoot = join(here, "..", "..", "..");
8
10
  /** Newest modification time under a file or directory, ignoring build output. */
@@ -110,6 +112,42 @@ async function waitPort(port, ms) {
110
112
  }
111
113
  return false;
112
114
  }
115
+ /** GET /healthz on the loopback port; true only for a 200. */
116
+ export function healthzUp(port) {
117
+ return new Promise((resolve) => {
118
+ const req = get({ host: "127.0.0.1", port, path: "/healthz", timeout: 3_000 }, (res) => {
119
+ res.resume();
120
+ resolve(res.statusCode === 200);
121
+ });
122
+ req.once("timeout", () => {
123
+ req.destroy();
124
+ resolve(false);
125
+ });
126
+ req.once("error", () => resolve(false));
127
+ });
128
+ }
129
+ /**
130
+ * One ledger, one body. The desktop used to build its own issuer and body on
131
+ * every open, which on a machine whose body starts at logon put the window on
132
+ * a second, empty ledger: the panel looked broken while the real decisions sat
133
+ * in the directory the lock names. So the lock is read first. Held by a live
134
+ * process that answers /healthz where this run was told to look, the panel
135
+ * joins that body. Held by a live process that does not answer there, the
136
+ * desktop stops: someone owns the ledger and is not where we were pointed, and
137
+ * a second body would be refused by the lock anyway. A dead or unreadable lock
138
+ * is the body's own to clear (`verax unlock`); the desktop builds as before.
139
+ */
140
+ export async function desktopMode(stateDir, bodyPort, probe = healthzUp) {
141
+ const lockPath = join(stateDir, "ledger.lock");
142
+ if (!existsSync(lockPath))
143
+ return { mode: "spawn" };
144
+ const lock = readLockFile(lockPath);
145
+ if (!lock || !pidAlive(lock.pid))
146
+ return { mode: "spawn" };
147
+ if (await probe(bodyPort))
148
+ return { mode: "attach", pid: lock.pid };
149
+ return { error: "desktop-body-locked", pid: lock.pid };
150
+ }
113
151
  export function killTree(pid) {
114
152
  if (pid == null)
115
153
  return;
@@ -206,36 +244,48 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
206
244
  killTree(c.pid);
207
245
  };
208
246
  try {
209
- const issuer = spawnLogged(process.execPath, ["--experimental-strip-types", issuerScript, "--out", tokenPath], issuerEnv(cleanEnv(), opts, audience, issuerUrl), repoRoot);
210
- kids.push(issuer);
211
- collectOutput(issuer, log);
212
- if (!(await waitPort(opts.issuerPort, 15_000))) {
213
- writeErr("desktop-issuer-timeout\n");
214
- stopAll();
215
- return 1;
216
- }
217
- const token = readFileSync(tokenPath, "utf8").trim();
218
- if (token === "") {
219
- writeErr("desktop-token-missing\n");
220
- stopAll();
247
+ const decided = await desktopMode(opts.stateDir, opts.bodyPort);
248
+ if ("error" in decided) {
249
+ writeErr(`${decided.error}:${decided.pid}\n`);
221
250
  return 1;
222
251
  }
223
- const body = spawnLogged(process.execPath, ["--experimental-strip-types", mainTs], {
224
- ...cleanEnv(),
225
- VERAX_STATE_DIR: opts.stateDir,
226
- VERAX_ISSUER: issuerUrl,
227
- VERAX_JWKS_URL: `${issuerUrl}/.well-known/jwks.json`,
228
- VERAX_AUDIENCE: audience,
229
- VERAX_BIND: `127.0.0.1:${opts.bodyPort}`,
230
- VERAX_POLICY_FILE: policy,
231
- ...(opts.inventoryFile ? { VERAX_INVENTORY_FILE: opts.inventoryFile } : {}),
232
- }, repoRoot);
233
- kids.push(body);
234
- collectOutput(body, log);
235
- if (!(await waitPort(opts.bodyPort, 15_000))) {
236
- writeErr("desktop-body-timeout\n");
237
- stopAll();
238
- return 1;
252
+ // Joining a running body: its issuer is whatever the body's resource
253
+ // metadata names, and its token is not ours to read. The panel's own
254
+ // origin has to be on that issuer's allow-list (VERAX_DEV_REDIRECT_URIS on
255
+ // the running issuer), which this run cannot set after the fact.
256
+ let token = null;
257
+ if (decided.mode === "spawn") {
258
+ const issuer = spawnLogged(process.execPath, ["--experimental-strip-types", issuerScript, "--out", tokenPath], issuerEnv(cleanEnv(), opts, audience, issuerUrl), repoRoot);
259
+ kids.push(issuer);
260
+ collectOutput(issuer, log);
261
+ if (!(await waitPort(opts.issuerPort, 15_000))) {
262
+ writeErr("desktop-issuer-timeout\n");
263
+ stopAll();
264
+ return 1;
265
+ }
266
+ token = readFileSync(tokenPath, "utf8").trim();
267
+ if (token === "") {
268
+ writeErr("desktop-token-missing\n");
269
+ stopAll();
270
+ return 1;
271
+ }
272
+ const body = spawnLogged(process.execPath, ["--experimental-strip-types", mainTs], {
273
+ ...cleanEnv(),
274
+ VERAX_STATE_DIR: opts.stateDir,
275
+ VERAX_ISSUER: issuerUrl,
276
+ VERAX_JWKS_URL: `${issuerUrl}/.well-known/jwks.json`,
277
+ VERAX_AUDIENCE: audience,
278
+ VERAX_BIND: `127.0.0.1:${opts.bodyPort}`,
279
+ VERAX_POLICY_FILE: policy,
280
+ ...(opts.inventoryFile ? { VERAX_INVENTORY_FILE: opts.inventoryFile } : {}),
281
+ }, repoRoot);
282
+ kids.push(body);
283
+ collectOutput(body, log);
284
+ if (!(await waitPort(opts.bodyPort, 15_000))) {
285
+ writeErr("desktop-body-timeout\n");
286
+ stopAll();
287
+ return 1;
288
+ }
239
289
  }
240
290
  const panelSources = [
241
291
  join(panelDir, "src"),
@@ -290,12 +340,14 @@ export async function runDesktop(opts, writeErr = (s) => process.stderr.write(s)
290
340
  const browser = spawnLogged(browserBin, browserArgv, cleanEnv(), repoRoot, false);
291
341
  kids.push(browser);
292
342
  collectOutput(browser, log);
293
- if (log.text.includes(token)) {
343
+ if (token !== null && log.text.includes(token)) {
294
344
  writeErr("desktop-token-leaked\n");
295
345
  stopAll();
296
346
  return 1;
297
347
  }
298
- process.stdout.write(`desktop-ready issuer=${opts.issuerPort} body=${opts.bodyPort} panel=${opts.panelPort}\n`);
348
+ process.stdout.write(decided.mode === "attach"
349
+ ? `desktop-ready body=${opts.bodyPort} panel=${opts.panelPort} attached=1 pid=${decided.pid}\n`
350
+ : `desktop-ready issuer=${opts.issuerPort} body=${opts.bodyPort} panel=${opts.panelPort}\n`);
299
351
  const onSignal = () => {
300
352
  stopAll();
301
353
  process.exit(1);