@verax-ai/body 0.6.1 → 0.7.0

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.
@@ -0,0 +1,18 @@
1
+ export declare const ALARM_OUTBOX_DIR = "alarm-outbox";
2
+ export declare const ALARM_HISTORY = "alarm-history.jsonl";
3
+ export declare const ALARM_EVENT_ID: RegExp;
4
+ export type AlarmEnvelope = {
5
+ payload: Record<string, unknown>;
6
+ sig: string;
7
+ };
8
+ export declare function isAlarmEventId(eventId: string): boolean;
9
+ /** A leaf name that cannot walk out of the outbox directory. */
10
+ export declare function isSafeOutboxEventId(eventId: string): boolean;
11
+ /** Same-name file beside the outbox directory. A folder here blocks the write. */
12
+ export declare const ALARM_OUTBOX_RECORD = "alarm-outbox.json";
13
+ export declare function hasAlarmOutbox(stateDir: string, eventId: string): boolean;
14
+ export declare function deliveredAlarmIds(stateDir: string): Set<string>;
15
+ export declare function hasAlarmDelivery(stateDir: string, eventId: string): boolean;
16
+ export declare function writeAlarmOutbox(stateDir: string, envelope: AlarmEnvelope): void;
17
+ export declare function listAlarmOutbox(stateDir: string): AlarmEnvelope[];
18
+ export declare function markAlarmDelivered(stateDir: string, envelope: AlarmEnvelope, now?: number): void;
@@ -0,0 +1,199 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, closeSync, existsSync, fstatSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, statSync, unlinkSync, writeSync, } from "node:fs";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ export const ALARM_OUTBOX_DIR = "alarm-outbox";
5
+ export const ALARM_HISTORY = "alarm-history.jsonl";
6
+ export const ALARM_EVENT_ID = /^[0-9a-f-]{36}$/i;
7
+ export function isAlarmEventId(eventId) {
8
+ if (!ALARM_EVENT_ID.test(eventId))
9
+ return false;
10
+ if (eventId.includes("/") || eventId.includes("\\") || eventId.includes(".."))
11
+ return false;
12
+ return true;
13
+ }
14
+ /** A leaf name that cannot walk out of the outbox directory. */
15
+ export function isSafeOutboxEventId(eventId) {
16
+ if (eventId === "" || eventId.includes("/") || eventId.includes("\\") || eventId.includes(".."))
17
+ return false;
18
+ return true;
19
+ }
20
+ function outboxDir(stateDir) {
21
+ return join(stateDir, ALARM_OUTBOX_DIR);
22
+ }
23
+ function outboxPath(stateDir, eventId) {
24
+ if (!isSafeOutboxEventId(eventId))
25
+ throw new Error("alarm-event-id-invalid");
26
+ const dir = resolve(outboxDir(stateDir));
27
+ const leaf = `${eventId}.json`;
28
+ const path = resolve(dir, leaf);
29
+ const rel = relative(dir, path);
30
+ if (rel === "" || isAbsolute(rel) || rel.startsWith("..") || rel.split(sep).includes("..")) {
31
+ throw new Error("alarm-outbox-path-escape");
32
+ }
33
+ if (path !== join(dir, leaf))
34
+ throw new Error("alarm-outbox-path-escape");
35
+ return path;
36
+ }
37
+ function isUnsupportedDirFsync(err) {
38
+ const code = err.code;
39
+ return code === "EPERM" || code === "EISDIR" || code === "EINVAL" || code === "ENOTSUP" || code === "ENOSYS";
40
+ }
41
+ function fsyncDir(dir) {
42
+ try {
43
+ const fd = openSync(dir, "r");
44
+ try {
45
+ fsyncSync(fd);
46
+ }
47
+ finally {
48
+ closeSync(fd);
49
+ }
50
+ }
51
+ catch (err) {
52
+ if (isUnsupportedDirFsync(err))
53
+ return;
54
+ throw err;
55
+ }
56
+ }
57
+ /** Temporary file, fsync, rename. A reader sees the old file or the new one. */
58
+ function writeFileDurable(finalPath, payload) {
59
+ const dir = dirname(finalPath);
60
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
61
+ fsyncDir(dir);
62
+ const tmp = `${finalPath}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
63
+ const fd = openSync(tmp, "w", 0o600);
64
+ try {
65
+ writeSync(fd, payload, 0, "utf8");
66
+ fsyncSync(fd);
67
+ }
68
+ finally {
69
+ closeSync(fd);
70
+ }
71
+ renameSync(tmp, finalPath);
72
+ try {
73
+ chmodSync(finalPath, 0o600);
74
+ }
75
+ catch {
76
+ // Windows may refuse chmod; the file is already written.
77
+ }
78
+ fsyncDir(dir);
79
+ }
80
+ /** Same-name file beside the outbox directory. A folder here blocks the write. */
81
+ export const ALARM_OUTBOX_RECORD = `${ALARM_OUTBOX_DIR}.json`;
82
+ function outboxRecordPath(stateDir) {
83
+ return join(stateDir, ALARM_OUTBOX_RECORD);
84
+ }
85
+ function readOutboxEnvelope(path) {
86
+ try {
87
+ if (!statSync(path).isFile())
88
+ return null;
89
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
90
+ if (!parsed || typeof parsed !== "object" || typeof parsed.sig !== "string" || parsed.sig === "")
91
+ return null;
92
+ if (!parsed.payload || typeof parsed.payload !== "object")
93
+ return null;
94
+ const id = parsed.payload.eventId;
95
+ if (typeof id !== "string" || !isSafeOutboxEventId(id))
96
+ return null;
97
+ return parsed;
98
+ }
99
+ catch {
100
+ return null;
101
+ }
102
+ }
103
+ export function hasAlarmOutbox(stateDir, eventId) {
104
+ if (!isSafeOutboxEventId(eventId))
105
+ return false;
106
+ const envelope = readOutboxEnvelope(outboxPath(stateDir, eventId));
107
+ return envelope !== null && envelope.payload.eventId === eventId;
108
+ }
109
+ export function deliveredAlarmIds(stateDir) {
110
+ const path = join(stateDir, ALARM_HISTORY);
111
+ if (!existsSync(path))
112
+ return new Set();
113
+ const raw = readFileSync(path, "utf8");
114
+ const ids = new Set();
115
+ for (const line of raw.split("\n")) {
116
+ if (line.trim() === "")
117
+ continue;
118
+ try {
119
+ const row = JSON.parse(line);
120
+ if (typeof row.eventId === "string" && isSafeOutboxEventId(row.eventId))
121
+ ids.add(row.eventId);
122
+ }
123
+ catch {
124
+ // A torn history line is not a delivery.
125
+ }
126
+ }
127
+ return ids;
128
+ }
129
+ export function hasAlarmDelivery(stateDir, eventId) {
130
+ return deliveredAlarmIds(stateDir).has(eventId);
131
+ }
132
+ function appendFileDurable(path, line) {
133
+ const dir = dirname(path);
134
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
135
+ const fd = openSync(path, "a+", 0o600);
136
+ try {
137
+ const size = fstatSync(fd).size;
138
+ if (size > 0) {
139
+ const last = Buffer.alloc(1);
140
+ if (readSync(fd, last, 0, 1, size - 1) === 1 && last[0] !== 0x0a) {
141
+ writeSync(fd, "\n", null, "utf8");
142
+ }
143
+ }
144
+ writeSync(fd, line, null, "utf8");
145
+ fsyncSync(fd);
146
+ }
147
+ finally {
148
+ closeSync(fd);
149
+ }
150
+ fsyncDir(dir);
151
+ }
152
+ export function writeAlarmOutbox(stateDir, envelope) {
153
+ const eventId = envelope.payload.eventId;
154
+ if (typeof eventId !== "string" || eventId === "")
155
+ throw new Error("alarm-event-id-missing");
156
+ if (!isSafeOutboxEventId(eventId))
157
+ throw new Error("alarm-event-id-invalid");
158
+ const body = `${JSON.stringify(envelope)}\n`;
159
+ writeFileDurable(outboxRecordPath(stateDir), body);
160
+ writeFileDurable(outboxPath(stateDir, eventId), body);
161
+ }
162
+ export function listAlarmOutbox(stateDir) {
163
+ const delivered = deliveredAlarmIds(stateDir);
164
+ const dir = outboxDir(stateDir);
165
+ if (!existsSync(dir))
166
+ return [];
167
+ const names = readdirSync(dir).filter((name) => name.endsWith(".json")).sort();
168
+ const out = [];
169
+ for (const name of names) {
170
+ const parsed = readOutboxEnvelope(join(dir, name));
171
+ if (!parsed)
172
+ continue;
173
+ const eventId = parsed.payload.eventId;
174
+ if (typeof eventId !== "string" || delivered.has(eventId))
175
+ continue;
176
+ out.push(parsed);
177
+ }
178
+ return out;
179
+ }
180
+ export function markAlarmDelivered(stateDir, envelope, now = Date.now()) {
181
+ const eventId = envelope.payload.eventId;
182
+ if (typeof eventId !== "string" || !isSafeOutboxEventId(eventId))
183
+ return;
184
+ const line = {
185
+ eventId,
186
+ deliveredAtMs: now,
187
+ triggerCode: envelope.payload.triggerCode,
188
+ };
189
+ appendFileDurable(join(stateDir, ALARM_HISTORY), `${JSON.stringify(line)}\n`);
190
+ for (const path of [outboxPath(stateDir, eventId), outboxRecordPath(stateDir)]) {
191
+ try {
192
+ unlinkSync(path);
193
+ }
194
+ catch (err) {
195
+ if (err.code !== "ENOENT")
196
+ throw err;
197
+ }
198
+ }
199
+ }
@@ -0,0 +1,16 @@
1
+ export declare const ALARM_POST_TIMEOUT_MS = 10000;
2
+ export declare function assertAlarmWebhookUrl(url: string): void;
3
+ /**
4
+ * POST the signed envelope. Redirects are not followed. A 2xx status is
5
+ * acceptance; the body is not read. Anything else, including a 302, is not
6
+ * delivery.
7
+ */
8
+ export declare function postAlarmWebhook(url: string, envelope: unknown, signal?: AbortSignal): Promise<boolean>;
9
+ /** Retry pending outbox files until each receiver answers 2xx. Same eventId every time. */
10
+ export declare function startAlarmDelivery(opts: {
11
+ stateDir: string;
12
+ url: string;
13
+ retryMs: number;
14
+ onTick?: () => void;
15
+ }): () => Promise<void>;
16
+ export declare function pokeAlarmDelivery(stateDir: string): void;
@@ -0,0 +1,106 @@
1
+ import { listAlarmOutbox, markAlarmDelivered } from "./alarm-outbox.js";
2
+ import { ALARM_WEBHOOK_URL_ERROR, isAllowedAlarmWebhookUrl } from "./config.js";
3
+ export const ALARM_POST_TIMEOUT_MS = 10_000;
4
+ export function assertAlarmWebhookUrl(url) {
5
+ if (!isAllowedAlarmWebhookUrl(url))
6
+ throw new Error(ALARM_WEBHOOK_URL_ERROR);
7
+ }
8
+ function oneLine(err) {
9
+ const text = err instanceof Error ? err.message : String(err);
10
+ return text.replace(/[\r\n]+/g, " ").slice(0, 300);
11
+ }
12
+ /**
13
+ * POST the signed envelope. Redirects are not followed. A 2xx status is
14
+ * acceptance; the body is not read. Anything else, including a 302, is not
15
+ * delivery.
16
+ */
17
+ export async function postAlarmWebhook(url, envelope, signal) {
18
+ const ac = new AbortController();
19
+ const onAbort = () => ac.abort();
20
+ if (signal) {
21
+ if (signal.aborted)
22
+ ac.abort();
23
+ else
24
+ signal.addEventListener("abort", onAbort, { once: true });
25
+ }
26
+ const timer = setTimeout(() => ac.abort(), ALARM_POST_TIMEOUT_MS);
27
+ try {
28
+ const res = await fetch(url, {
29
+ method: "POST",
30
+ headers: { "content-type": "application/json" },
31
+ body: JSON.stringify(envelope),
32
+ redirect: "manual",
33
+ signal: ac.signal,
34
+ });
35
+ const body = res.body;
36
+ if (body) {
37
+ try {
38
+ body.cancel();
39
+ }
40
+ catch {
41
+ // Closing an unread body is enough; a cancel that throws is not delivery.
42
+ }
43
+ }
44
+ return res.status >= 200 && res.status < 300;
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ finally {
50
+ clearTimeout(timer);
51
+ signal?.removeEventListener("abort", onAbort);
52
+ }
53
+ }
54
+ const pokers = new Map();
55
+ /** Retry pending outbox files until each receiver answers 2xx. Same eventId every time. */
56
+ export function startAlarmDelivery(opts) {
57
+ assertAlarmWebhookUrl(opts.url);
58
+ let stopped = false;
59
+ let inFlight = false;
60
+ let running = Promise.resolve();
61
+ const abort = new AbortController();
62
+ const tick = () => {
63
+ if (stopped || inFlight)
64
+ return;
65
+ inFlight = true;
66
+ running = (async () => {
67
+ try {
68
+ try {
69
+ opts.onTick?.();
70
+ }
71
+ catch (err) {
72
+ process.stderr.write(`verax: alarm-delivery: ${oneLine(err)}\n`);
73
+ }
74
+ for (const envelope of listAlarmOutbox(opts.stateDir)) {
75
+ if (stopped)
76
+ break;
77
+ const ok = await postAlarmWebhook(opts.url, envelope, abort.signal);
78
+ if (stopped)
79
+ break;
80
+ if (ok)
81
+ markAlarmDelivered(opts.stateDir, envelope);
82
+ }
83
+ }
84
+ catch (err) {
85
+ process.stderr.write(`verax: alarm-delivery: ${oneLine(err)}\n`);
86
+ }
87
+ finally {
88
+ inFlight = false;
89
+ }
90
+ })();
91
+ };
92
+ pokers.set(opts.stateDir, tick);
93
+ tick();
94
+ const timer = setInterval(tick, opts.retryMs);
95
+ timer.unref();
96
+ return async () => {
97
+ stopped = true;
98
+ abort.abort();
99
+ pokers.delete(opts.stateDir);
100
+ clearInterval(timer);
101
+ await running;
102
+ };
103
+ }
104
+ export function pokeAlarmDelivery(stateDir) {
105
+ pokers.get(stateDir)?.();
106
+ }
@@ -257,7 +257,7 @@ export async function runApprove(argv, writeErr = (s) => process.stderr.write(s)
257
257
  return 1;
258
258
  }
259
259
  try {
260
- const signers = loadOrCreateSigners(stateDir);
260
+ const signers = loadOrCreateSigners(stateDir, env.VERAX_KEYS_DIR);
261
261
  const approvals = approvalsLogFor(ledger);
262
262
  const decisions = await ledger.decisions();
263
263
  const defer = decisions.find((d) => d.claims.ref === ref && d.claims.decision === "defer");
package/dist/cli.js CHANGED
@@ -21,6 +21,8 @@ import { runVerify } from "./verify-cli.js";
21
21
  import { runUnlock } from "./unlock.js";
22
22
  import { runWitness } from "./witness.js";
23
23
  import { runWatch } from "./watch.js";
24
+ import { runMemoryRehead } from "./memory-rehead-cli.js";
25
+ import { runMemoryReattest } from "./memory-reattest-cli.js";
24
26
  const HELP = `verax - the body an agent asks before it acts, and the ledger it answers from.
25
27
 
26
28
  Usage: verax <command> [options]
@@ -69,6 +71,12 @@ Usage: verax <command> [options]
69
71
  halt <stateDir> stop the body from allowing anything further
70
72
  resume <stateDir> lift a halt; who and when go to halt-history.jsonl
71
73
  unlock [--force] <stateDir> clear a stale ledger lock
74
+ memory reattest <stateDir>
75
+ convert 0.6.1 flat memory files to signed V2 revisions.
76
+ The body must be stopped.
77
+ memory rehead <stateDir>
78
+ write a signed head from the current commit chain.
79
+ The body must be stopped.
72
80
 
73
81
  --help, -h print this
74
82
  --version, -v print the version
@@ -333,6 +341,12 @@ async function dispatchCli(argv, stdout, stderr, env) {
333
341
  await runWitness(stateDir);
334
342
  return 0;
335
343
  }
344
+ if (argv[0] === "memory") {
345
+ if (argv[1] === "rehead") {
346
+ return runMemoryRehead(argv.slice(1), stdout, stderr, env);
347
+ }
348
+ return runMemoryReattest(argv.slice(1), stdout, stderr, env);
349
+ }
336
350
  const head = argv[0];
337
351
  if (head !== undefined && !head.startsWith("--")) {
338
352
  stderr.write(`unknown command: ${terminalText(head)}\n`);
package/dist/config.d.ts CHANGED
@@ -46,6 +46,27 @@ export type BodyConfig = {
46
46
  messageQuotaBytes?: number;
47
47
  /** The operator door, a second listener. Null leaves it shut. */
48
48
  operatorDoor?: OperatorDoorConfig | null;
49
+ /**
50
+ * Directory holding record/effect signer PEMs. Default is `<stateDir>/keys`.
51
+ * `VERAX_KEYS_DIR` sets this when the keys must sit outside the state directory.
52
+ */
53
+ keysDir?: string;
54
+ /**
55
+ * Directory holding the signed memory head. Default is the keys directory.
56
+ * `VERAX_MEMORY_HEAD_DIR` sets this when the head must sit outside both.
57
+ */
58
+ headDir?: string;
59
+ /**
60
+ * HTTPS webhook that receives a signed integrity incident. `http` is
61
+ * accepted only for 127.0.0.1, [::1], and localhost. `VERAX_ALARM_WEBHOOK_URL`
62
+ * sets this the same way `VERAX_KEYS_DIR` sets `keysDir`.
63
+ */
64
+ alarmWebhookUrl?: string;
65
+ /**
66
+ * How often the body retries an undelivered alarm, in milliseconds.
67
+ * Default 30000; floor 100. `VERAX_ALARM_RETRY_MS` sets this.
68
+ */
69
+ alarmRetryMs?: number;
49
70
  };
50
71
  export type OperatorDoorConfig = {
51
72
  /** The one origin the door answers for. It is the passkey relying party. */
@@ -69,6 +90,12 @@ export type ConfigResult = {
69
90
  code: typeof EX_CONFIG;
70
91
  };
71
92
  export declare function isLoopbackHost(host: string): boolean;
93
+ export declare const DEFAULT_ALARM_RETRY_MS = 30000;
94
+ export declare const MIN_ALARM_RETRY_MS = 100;
95
+ /** An https URL, or http on 127.0.0.1 / [::1] / localhost. Anything else is refused at start. */
96
+ export declare function isAllowedAlarmWebhookUrl(raw: string): boolean;
97
+ export declare const ALARM_WEBHOOK_URL_ERROR = "alarm webhook URL needs https (or http on 127.0.0.1, [::1], or localhost)";
98
+ export declare function alarmRetryMs(raw?: string | number): number;
72
99
  /** A directory or an unreadable file. A path that is not there is left to the read. */
73
100
  export declare function policyFileRefusal(path: string): string | null;
74
101
  /**
package/dist/config.js CHANGED
@@ -36,6 +36,30 @@ export function isLoopbackHost(host) {
36
36
  const stripped = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
37
37
  return LOOPBACK.has(stripped);
38
38
  }
39
+ export const DEFAULT_ALARM_RETRY_MS = 30_000;
40
+ export const MIN_ALARM_RETRY_MS = 100;
41
+ /** An https URL, or http on 127.0.0.1 / [::1] / localhost. Anything else is refused at start. */
42
+ export function isAllowedAlarmWebhookUrl(raw) {
43
+ let url;
44
+ try {
45
+ url = new URL(raw);
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ if (url.protocol === "https:")
51
+ return true;
52
+ return url.protocol === "http:" && isLoopbackHost(url.hostname);
53
+ }
54
+ export const ALARM_WEBHOOK_URL_ERROR = "alarm webhook URL needs https (or http on 127.0.0.1, [::1], or localhost)";
55
+ export function alarmRetryMs(raw) {
56
+ if (raw === undefined || raw === "")
57
+ return DEFAULT_ALARM_RETRY_MS;
58
+ const n = typeof raw === "number" ? raw : Number(raw);
59
+ if (!Number.isFinite(n))
60
+ return DEFAULT_ALARM_RETRY_MS;
61
+ return Math.max(MIN_ALARM_RETRY_MS, Math.floor(n));
62
+ }
39
63
  function jwksPinParses(raw) {
40
64
  try {
41
65
  const parsed = JSON.parse(raw);
@@ -186,6 +210,13 @@ export function loadConfig(env) {
186
210
  }
187
211
  const inventoryRaw = env.VERAX_INVENTORY_FILE?.trim() ?? "";
188
212
  const downstreamRaw = env.VERAX_DOWNSTREAM?.trim() ?? "";
213
+ const keysDirRaw = env.VERAX_KEYS_DIR?.trim() ?? "";
214
+ const headDirRaw = env.VERAX_MEMORY_HEAD_DIR?.trim() ?? "";
215
+ const alarmWebhookRaw = env.VERAX_ALARM_WEBHOOK_URL?.trim() ?? "";
216
+ if (alarmWebhookRaw !== "" && !isAllowedAlarmWebhookUrl(alarmWebhookRaw)) {
217
+ return { ok: false, code: EX_CONFIG, reason: ALARM_WEBHOOK_URL_ERROR };
218
+ }
219
+ const alarmRetryRaw = env.VERAX_ALARM_RETRY_MS?.trim() ?? "";
189
220
  return {
190
221
  ok: true,
191
222
  value: {
@@ -201,6 +232,10 @@ export function loadConfig(env) {
201
232
  tlsTerminated,
202
233
  inventoryFile: inventoryRaw === "" ? null : inventoryRaw,
203
234
  downstreamFile: downstreamRaw === "" ? null : downstreamRaw,
235
+ ...(keysDirRaw !== "" ? { keysDir: keysDirRaw } : {}),
236
+ ...(headDirRaw !== "" ? { headDir: headDirRaw } : {}),
237
+ ...(alarmWebhookRaw !== "" ? { alarmWebhookUrl: alarmWebhookRaw } : {}),
238
+ ...(alarmRetryRaw !== "" ? { alarmRetryMs: alarmRetryMs(alarmRetryRaw) } : {}),
204
239
  allowedOrigins: (env.VERAX_ALLOWED_ORIGINS ?? "")
205
240
  .split(",")
206
241
  .map((item) => item.trim())
@@ -37,6 +37,7 @@ export type ControlSignatureReport = {
37
37
  unsignedHttp: number;
38
38
  cli: number;
39
39
  file: number;
40
+ integrity: number;
40
41
  line: string;
41
42
  trustSource: "pinned" | "in-ledger" | "none";
42
43
  trustNote: string;
@@ -14,6 +14,7 @@ import { canonical } from "@cedulon/core";
14
14
  import { listPieceFiles } from "@verax-ai/proxy";
15
15
  import { asAssertion, assertionMatches, indexRemovalMark, noteChainRemoval, passkeyRemovedAt, readLines, signedAfterRemovalSegment, trustOf, } from "./approval-signature.js";
16
16
  import { historyTail } from "./halt.js";
17
+ import { INCIDENT_BY } from "./incidents.js";
17
18
  import { credentialsPath, findCredential, hasRegisteredOperator, readCredentialsAt, updateCounter, } from "./operator-credentials.js";
18
19
  import { readRpConfig } from "./rp-config.js";
19
20
  import { verifyAssertion } from "./webauthn-verify.js";
@@ -73,6 +74,9 @@ export function gateControlSignature(opts) {
73
74
  },
74
75
  };
75
76
  }
77
+ function integrityAccepted(control, action) {
78
+ return action === "halt" && control.via === "integrity" && control.by === INCIDENT_BY;
79
+ }
76
80
  function controlSignatureOf(value) {
77
81
  if (!value || typeof value !== "object")
78
82
  return null;
@@ -133,6 +137,7 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
133
137
  let unsignedHttp = 0;
134
138
  let cli = 0;
135
139
  let file = 0;
140
+ let integrity = 0;
136
141
  const lineHashByLine = new Map();
137
142
  const used = new Set();
138
143
  // Ledger order, not history-line order. A removal between two control
@@ -153,7 +158,14 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
153
158
  if (!control)
154
159
  continue;
155
160
  const at = typeof control.line === "number" && Number.isInteger(control.line) ? control.line : -1;
156
- if (control.signature === undefined) {
161
+ const action = claims.subject === "verax.halt" ? "halt" : "resume";
162
+ if (control.via === "integrity") {
163
+ if (integrityAccepted(control, action) && control.signature === undefined)
164
+ integrity += 1;
165
+ else
166
+ signedFailed += 1;
167
+ }
168
+ else if (control.signature === undefined) {
157
169
  if (control.via === "http")
158
170
  unsignedHttp += 1;
159
171
  else if (control.via === "cli")
@@ -164,7 +176,6 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
164
176
  else {
165
177
  const sig = controlSignatureOf(control.signature);
166
178
  const expectedPrev = at === 0 ? null : at > 0 ? lineHashByLine.get(at - 1) : undefined;
167
- const action = claims.subject === "verax.halt" ? "halt" : "resume";
168
179
  const challenge = sig && expectedPrev !== undefined && sig.prev === expectedPrev
169
180
  ? controlChallenge({ action, prev: expectedPrev })
170
181
  : null;
@@ -192,7 +203,8 @@ export async function verifyControlSignatures(stateDir, opts = {}) {
192
203
  unsignedHttp,
193
204
  cli,
194
205
  file,
195
- line: `control signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli} · file ${file}${signedAfterRemovalSegment(signedAfterRemoval)}`,
206
+ integrity,
207
+ line: `control signatures signed-verified ${signedVerified} · signed-failed ${signedFailed} · unsigned-http ${unsignedHttp} · cli ${cli} · file ${file} · integrity ${integrity}${signedAfterRemovalSegment(signedAfterRemoval)}`,
196
208
  trustSource: trust.trustSource,
197
209
  trustNote: trust.trustNote,
198
210
  };
package/dist/doctor.js CHANGED
@@ -10,6 +10,7 @@ import { lockHolderAlive, lockState } from "@verax-ai/proxy";
10
10
  import { readLockFile } from "./unlock.js";
11
11
  import { pendingAnchors } from "./anchor-cli.js";
12
12
  import { readWitnessListen } from "./witness.js";
13
+ import { pathIsInsideDir, resolveKeysDir } from "./keys.js";
13
14
  const SECRET_RE = /sk-|-----BEGIN|Bearer |eyJ[A-Za-z0-9_-]{10,}\./;
14
15
  const SECRET_NAME = /^(VERAX_DEV_TOKEN|.*_(TOKEN|SECRET|KEY))$/;
15
16
  /**
@@ -133,6 +134,14 @@ export function runDoctor(env, argv, opts = {}) {
133
134
  const custody = keyCustodyCheck(stateDir, env, opts.elevated ?? (() => defaultElevated()), opts.keyOwner ?? defaultKeyOwner);
134
135
  if (custody)
135
136
  checks.push(custody);
137
+ const keysDir = resolveKeysDir(stateDir, env.VERAX_KEYS_DIR);
138
+ if (pathIsInsideDir(stateDir, keysDir)) {
139
+ checks.push({
140
+ id: "record-key-location",
141
+ level: "warn",
142
+ detail: "record key is inside the state directory; a state-directory writer also holds the key. Set VERAX_KEYS_DIR to a directory outside the state directory.",
143
+ });
144
+ }
136
145
  }
137
146
  const secretNames = Object.entries(env)
138
147
  .filter(([k, v]) => Boolean(v) && ((SECRET_NAME.test(k) && !PUBLIC_KEY_PATH_NAMES.has(k)) || SECRET_RE.test(String(v))))
package/dist/halt.d.ts CHANGED
@@ -1,7 +1,12 @@
1
- import type { ControlSignature } from "@verax-ai/proxy";
1
+ import { type ControlSignature } from "@verax-ai/proxy";
2
2
  /**
3
- * The proxy refuses every call while `<stateDir>/halted` exists; that file is
4
- * the switch and stays empty. Who flipped it and when goes to
3
+ * The proxy refuses every call while `<stateDir>/halted` is a regular file, or
4
+ * while this process has marked a halt that could not persist that file.
5
+ * The process flag is set only when that write fails; a written file is the
6
+ * single source of truth, so a later `verax resume` in another process can
7
+ * lift a normal halt by removing the file. A flag-only halt (path blocked)
8
+ * is lifted in this process by `resumeBody` — HTTP `POST /api/resume`.
9
+ * The file is the switch and stays empty. Who flipped it and when goes to
5
10
  * `halt-history.jsonl` beside it, one line per halt or resume, so the panel
6
11
  * can say "stopped by operator-7 at 14:02" and a resume is not silent.
7
12
  *
@@ -15,18 +20,29 @@ import type { ControlSignature } from "@verax-ai/proxy";
15
20
  *
16
21
  * An HTTP halt or resume made with the operator's passkey carries that
17
22
  * assertion on its line, and the control record carries it on from there.
23
+ * A memory integrity failure uses `via: "integrity"` and
24
+ * `by: "verax:memory-integrity"`.
18
25
  */
19
26
  export type HaltEvent = {
20
27
  action: "halt" | "resume";
21
28
  atMs: number;
22
29
  by: string;
23
- via: "cli" | "http";
30
+ via: "cli" | "http" | "integrity";
24
31
  signature?: ControlSignature;
32
+ /** Integrity halt only: the incident this switch is bound to. */
33
+ eventId?: string;
34
+ triggerCode?: string;
35
+ memoryHead?: {
36
+ seq: number;
37
+ lastHash: string;
38
+ };
25
39
  };
26
40
  export type HaltState = {
27
41
  halted: boolean;
28
42
  since?: HaltEvent;
29
43
  };
44
+ /** The switch is an empty file. A folder at the path is a blocked write, not a halt. */
45
+ export declare function isHaltSwitchFile(stateDir: string): boolean;
30
46
  /**
31
47
  * SHA-256 of the newest history line, as the control record names that line
32
48
  * (`lineHash`), or `null` when there is none. A signed halt or resume binds
@@ -35,13 +51,16 @@ export type HaltState = {
35
51
  export declare function historyTail(stateDir: string): string | null;
36
52
  export declare function readHalt(stateDir: string): HaltState;
37
53
  /** Halting twice is one halt: the first line keeps saying who stopped it. */
38
- export declare function haltBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number, signature?: ControlSignature): HaltState;
54
+ export declare function haltBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number, signature?: ControlSignature, incident?: Pick<HaltEvent, "eventId" | "triggerCode" | "memoryHead">): HaltState;
39
55
  /**
40
56
  * Resuming a body that is not halted changes nothing and writes nothing.
41
- * The line goes to the history before the switch is removed: if it cannot be
42
- * written, the append throws and the body stays halted, rather than running
43
- * again with no record of who let it.
57
+ * Undelivered incidents are verified/re-signed and written to the outbox, or
58
+ * marked closed-pending-delivery with an atomic write. If that mark cannot be
59
+ * written, this throws and the body stays halted. The history line is
60
+ * appended after the mark: if the append throws, the body stays halted
61
+ * rather than running again with no record of who let it. Then the switch
62
+ * is removed. A later integrity halt is a new event. Pending outbox files stay.
44
63
  */
45
- export declare function resumeBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number, signature?: ControlSignature): HaltState;
64
+ export declare function resumeBody(stateDir: string, by: string, via: HaltEvent["via"], now?: number, signature?: ControlSignature, keysDir?: string | null): HaltState;
46
65
  export declare function runHalt(stateDir: string, writeErr?: (s: string) => void): number;
47
66
  export declare function runResume(stateDir: string, writeErr?: (s: string) => void): number;