@verax-ai/body 0.6.0 → 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
@@ -1,4 +1,6 @@
1
1
  export declare const EX_CONFIG = 78;
2
+ /** A start error whose message begins with this is one stderr line and exit 78. */
3
+ export declare const POLICY_FILE_ERROR_PREFIX = "VERAX_POLICY_FILE ";
2
4
  export type BodyConfig = {
3
5
  issuer: string;
4
6
  jwksUrl: string;
@@ -44,6 +46,27 @@ export type BodyConfig = {
44
46
  messageQuotaBytes?: number;
45
47
  /** The operator door, a second listener. Null leaves it shut. */
46
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;
47
70
  };
48
71
  export type OperatorDoorConfig = {
49
72
  /** The one origin the door answers for. It is the passkey relying party. */
@@ -67,6 +90,14 @@ export type ConfigResult = {
67
90
  code: typeof EX_CONFIG;
68
91
  };
69
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;
99
+ /** A directory or an unreadable file. A path that is not there is left to the read. */
100
+ export declare function policyFileRefusal(path: string): string | null;
70
101
  /**
71
102
  * `VERAX_OPERATOR_DOOR` names the origin an operator reaches the door at. It
72
103
  * is HTTPS, or `http://localhost` for a trial on the machine itself, and it
package/dist/config.js CHANGED
@@ -1,5 +1,7 @@
1
- import { readFileSync } from "node:fs";
1
+ import { readFileSync, statSync } from "node:fs";
2
2
  export const EX_CONFIG = 78;
3
+ /** A start error whose message begins with this is one stderr line and exit 78. */
4
+ export const POLICY_FILE_ERROR_PREFIX = "VERAX_POLICY_FILE ";
3
5
  /** Per-tenant `memory.put` cap. The HTTP body cap does not reset this total. */
4
6
  export const DEFAULT_MEMORY_QUOTA_BYTES = 1024 * 1024;
5
7
  /** Per-tenant `message.send` cap. The HTTP body cap does not reset this total. */
@@ -34,6 +36,30 @@ export function isLoopbackHost(host) {
34
36
  const stripped = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
35
37
  return LOOPBACK.has(stripped);
36
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
+ }
37
63
  function jwksPinParses(raw) {
38
64
  try {
39
65
  const parsed = JSON.parse(raw);
@@ -47,6 +73,30 @@ function jwksPinParses(raw) {
47
73
  return null;
48
74
  }
49
75
  }
76
+ /** A directory or an unreadable file. A path that is not there is left to the read. */
77
+ export function policyFileRefusal(path) {
78
+ let st;
79
+ try {
80
+ st = statSync(path);
81
+ }
82
+ catch (err) {
83
+ const code = err.code;
84
+ if (code === "ENOENT")
85
+ return null;
86
+ return `${POLICY_FILE_ERROR_PREFIX}is missing or unreadable: ${path}`;
87
+ }
88
+ if (st.isDirectory())
89
+ return `${POLICY_FILE_ERROR_PREFIX}is a directory: ${path}`;
90
+ if (!st.isFile())
91
+ return `${POLICY_FILE_ERROR_PREFIX}is missing or unreadable: ${path}`;
92
+ try {
93
+ readFileSync(path);
94
+ }
95
+ catch {
96
+ return `${POLICY_FILE_ERROR_PREFIX}is missing or unreadable: ${path}`;
97
+ }
98
+ return null;
99
+ }
50
100
  function jwksFileParses(path) {
51
101
  try {
52
102
  const parsed = JSON.parse(readFileSync(path, "utf8"));
@@ -150,12 +200,23 @@ export function loadConfig(env) {
150
200
  if (policyFile === "") {
151
201
  return { ok: false, code: EX_CONFIG, reason: "missing VERAX_POLICY_FILE" };
152
202
  }
203
+ const policyRefusal = policyFileRefusal(policyFile);
204
+ if (policyRefusal) {
205
+ return { ok: false, code: EX_CONFIG, reason: policyRefusal };
206
+ }
153
207
  const door = readOperatorDoor(env);
154
208
  if (!door.ok) {
155
209
  return { ok: false, code: EX_CONFIG, reason: door.reason };
156
210
  }
157
211
  const inventoryRaw = env.VERAX_INVENTORY_FILE?.trim() ?? "";
158
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() ?? "";
159
220
  return {
160
221
  ok: true,
161
222
  value: {
@@ -171,6 +232,10 @@ export function loadConfig(env) {
171
232
  tlsTerminated,
172
233
  inventoryFile: inventoryRaw === "" ? null : inventoryRaw,
173
234
  downstreamFile: downstreamRaw === "" ? null : downstreamRaw,
235
+ ...(keysDirRaw !== "" ? { keysDir: keysDirRaw } : {}),
236
+ ...(headDirRaw !== "" ? { headDir: headDirRaw } : {}),
237
+ ...(alarmWebhookRaw !== "" ? { alarmWebhookUrl: alarmWebhookRaw } : {}),
238
+ ...(alarmRetryRaw !== "" ? { alarmRetryMs: alarmRetryMs(alarmRetryRaw) } : {}),
174
239
  allowedOrigins: (env.VERAX_ALLOWED_ORIGINS ?? "")
175
240
  .split(",")
176
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))))