@verax-ai/body 0.6.1 → 0.8.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,627 @@
1
+ import { createHash, createPrivateKey, createPublicKey, randomBytes, randomUUID, sign, verify } from "node:crypto";
2
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeSync, } from "node:fs";
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { canonical } from "@cedulon/core";
5
+ import { hasAlarmDelivery, hasAlarmOutbox, isAlarmEventId, writeAlarmOutbox, } from "./alarm-outbox.js";
6
+ import { haltBody, isHaltSwitchFile, readHalt } from "./halt.js";
7
+ import { assertRecordKeyTrust, resolveKeysDir } from "./keys.js";
8
+ import { markHistoryUnavailable } from "./memory-store.js";
9
+ export const INCIDENT_BY = "verax:memory-integrity";
10
+ export const INCIDENT_RECORD = "incident.json";
11
+ export const INCIDENTS_DIR = "incidents";
12
+ const INTEGRITY_REASONS = new Set([
13
+ "memory-integrity-mismatch",
14
+ "memory-integrity-missing",
15
+ "memory-integrity-unattested",
16
+ "memory-integrity-history-unavailable",
17
+ ]);
18
+ export function recordKeyId(publicKeyPem) {
19
+ const der = createPublicKey(publicKeyPem).export({ type: "spki", format: "der" });
20
+ return createHash("sha256").update(der).digest("hex").slice(0, 16);
21
+ }
22
+ function uuidFromHex(hex) {
23
+ const h = hex.toLowerCase().replace(/[^0-9a-f]/g, "").padEnd(32, "0").slice(0, 32);
24
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20, 32)}`;
25
+ }
26
+ function uuidFromBytes(buf) {
27
+ const b = Buffer.from(buf);
28
+ b[6] = (b[6] & 0x0f) | 0x40;
29
+ b[8] = (b[8] & 0x3f) | 0x80;
30
+ return uuidFromHex(b.toString("hex"));
31
+ }
32
+ /**
33
+ * randomUUID, then randomBytes, then a SHA-256 UUID of observedAt+trigger+record key.
34
+ * Generators are a parameter so a failing producer can be injected; that is
35
+ * dependency injection, not a product-code test hook. The last resort is
36
+ * stable for the same inputs (a retry of one incident stays one id).
37
+ */
38
+ export function incidentEventIdFrom(opts, generators) {
39
+ try {
40
+ return generators.randomUUID();
41
+ }
42
+ catch {
43
+ // RNG may refuse; keep going.
44
+ }
45
+ try {
46
+ return uuidFromBytes(generators.randomBytes(16));
47
+ }
48
+ catch {
49
+ // Same: fall through to a deterministic identity.
50
+ }
51
+ return lastResortIncidentId(opts, "");
52
+ }
53
+ const fallbackAlloc = { seq: 0 };
54
+ function lastResortIncidentId(opts, unique) {
55
+ try {
56
+ const keyId = recordKeyId(opts.publicKeyPem);
57
+ const material = unique
58
+ ? `${opts.observedAt}\0${opts.triggerCode}\0${keyId}\0${unique}`
59
+ : `${opts.observedAt}\0${opts.triggerCode}\0${keyId}`;
60
+ return uuidFromHex(createHash("sha256").update(material, "utf8").digest("hex"));
61
+ }
62
+ catch {
63
+ const material = unique ? `${opts.observedAt}\0${unique}` : String(opts.observedAt);
64
+ return uuidFromHex(createHash("sha256").update(material, "utf8").digest("hex"));
65
+ }
66
+ }
67
+ /** Production path: the same cascade; last resort mixes pid, a counter, and extra bytes. */
68
+ export function allocateIncidentEventId(opts) {
69
+ try {
70
+ return randomUUID();
71
+ }
72
+ catch {
73
+ // RNG may refuse; keep going.
74
+ }
75
+ try {
76
+ return uuidFromBytes(randomBytes(16));
77
+ }
78
+ catch {
79
+ // Same: fall through to a unique last resort.
80
+ }
81
+ fallbackAlloc.seq += 1;
82
+ let entropy = "";
83
+ try {
84
+ entropy = randomBytes(8).toString("hex");
85
+ }
86
+ catch {
87
+ // Extra bytes are optional; pid + counter still separate two allocations.
88
+ }
89
+ return lastResortIncidentId(opts, `${process.pid}\0${fallbackAlloc.seq}\0${entropy}`);
90
+ }
91
+ export function signIncident(payload, privateKeyPem) {
92
+ const sig = sign(null, Buffer.from(canonical(payload), "utf8"), createPrivateKey(privateKeyPem)).toString("base64");
93
+ return { payload, sig };
94
+ }
95
+ function isIntegrityReason(value) {
96
+ return INTEGRITY_REASONS.has(value);
97
+ }
98
+ function oneLine(err) {
99
+ const text = err instanceof Error ? err.message : String(err);
100
+ return text.replace(/[\r\n]+/g, " ").slice(0, 300);
101
+ }
102
+ function isUnsupportedDirFsync(err) {
103
+ const code = err.code;
104
+ return code === "EPERM" || code === "EISDIR" || code === "EINVAL" || code === "ENOTSUP" || code === "ENOSYS";
105
+ }
106
+ function fsyncDir(dir) {
107
+ try {
108
+ const fd = openSync(dir, "r");
109
+ try {
110
+ fsyncSync(fd);
111
+ }
112
+ finally {
113
+ closeSync(fd);
114
+ }
115
+ }
116
+ catch (err) {
117
+ if (isUnsupportedDirFsync(err))
118
+ return;
119
+ throw err;
120
+ }
121
+ }
122
+ function writeJsonDurable(path, value) {
123
+ const dir = dirname(path);
124
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
125
+ fsyncDir(dir);
126
+ const tmp = `${path}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`;
127
+ const fd = openSync(tmp, "w", 0o600);
128
+ try {
129
+ writeSync(fd, `${JSON.stringify(value)}\n`, 0, "utf8");
130
+ fsyncSync(fd);
131
+ }
132
+ finally {
133
+ closeSync(fd);
134
+ }
135
+ renameSync(tmp, path);
136
+ try {
137
+ chmodSync(path, 0o600);
138
+ }
139
+ catch {
140
+ // Windows may refuse chmod; the file is already written.
141
+ }
142
+ fsyncDir(dir);
143
+ }
144
+ function incidentEventPath(stateDir, eventId) {
145
+ if (!isAlarmEventId(eventId))
146
+ throw new Error("incident-event-id-invalid");
147
+ const dir = resolve(join(stateDir, INCIDENTS_DIR));
148
+ const leaf = `${eventId}.json`;
149
+ const path = resolve(dir, leaf);
150
+ const rel = relative(dir, path);
151
+ if (rel === "" || isAbsolute(rel) || rel.startsWith("..") || rel.split(sep).includes("..")) {
152
+ throw new Error("incident-path-escape");
153
+ }
154
+ if (path !== join(dir, leaf))
155
+ throw new Error("incident-path-escape");
156
+ return path;
157
+ }
158
+ function legacyIncidentPath(stateDir) {
159
+ return join(stateDir, INCIDENT_RECORD);
160
+ }
161
+ function parseStoredIncident(raw) {
162
+ try {
163
+ const row = JSON.parse(raw);
164
+ if (typeof row.eventId !== "string" || !isAlarmEventId(row.eventId))
165
+ return null;
166
+ if (typeof row.triggerCode !== "string" || !isIntegrityReason(row.triggerCode))
167
+ return null;
168
+ if (typeof row.observedAt !== "number" || !Number.isFinite(row.observedAt))
169
+ return null;
170
+ const stored = {
171
+ eventId: row.eventId,
172
+ triggerCode: row.triggerCode,
173
+ observedAt: row.observedAt,
174
+ };
175
+ const head = row.memoryHead;
176
+ if (head && typeof head === "object" && typeof head.seq === "number" && typeof head.lastHash === "string") {
177
+ stored.memoryHead = { seq: head.seq, lastHash: head.lastHash };
178
+ }
179
+ if (row.envelope && typeof row.envelope === "object" && typeof row.envelope.sig === "string") {
180
+ const payload = row.envelope.payload;
181
+ if (payload &&
182
+ typeof payload === "object" &&
183
+ payload.eventId === row.eventId &&
184
+ typeof payload.triggerCode === "string" &&
185
+ isIntegrityReason(payload.triggerCode)) {
186
+ stored.envelope = row.envelope;
187
+ }
188
+ }
189
+ if (row.closedPendingDelivery === true)
190
+ stored.closedPendingDelivery = true;
191
+ return stored;
192
+ }
193
+ catch {
194
+ return null;
195
+ }
196
+ }
197
+ function readIncidentFromPath(path) {
198
+ let raw;
199
+ try {
200
+ raw = readFileSync(path, "utf8");
201
+ }
202
+ catch {
203
+ return null;
204
+ }
205
+ return parseStoredIncident(raw);
206
+ }
207
+ function legacyMigrationComplete(stateDir, legacy) {
208
+ try {
209
+ const dest = incidentEventPath(stateDir, legacy.eventId);
210
+ if (!existsSync(dest) || !statSync(dest).isFile())
211
+ return false;
212
+ const stored = readIncidentFromPath(dest);
213
+ return stored !== null && stored.eventId === legacy.eventId;
214
+ }
215
+ catch {
216
+ return false;
217
+ }
218
+ }
219
+ function migrateLegacyIncident(stateDir) {
220
+ const legacy = readIncidentFromPath(legacyIncidentPath(stateDir));
221
+ if (!legacy)
222
+ return;
223
+ if (legacyMigrationComplete(stateDir, legacy))
224
+ return;
225
+ let dest;
226
+ try {
227
+ dest = incidentEventPath(stateDir, legacy.eventId);
228
+ }
229
+ catch {
230
+ return;
231
+ }
232
+ try {
233
+ if (existsSync(dest) && !statSync(dest).isFile()) {
234
+ process.stderr.write("verax: incident: legacy migrate target is not a file\n");
235
+ return;
236
+ }
237
+ writeJsonDurable(dest, legacy);
238
+ }
239
+ catch (err) {
240
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
241
+ }
242
+ }
243
+ function listIncidentRecords(stateDir) {
244
+ migrateLegacyIncident(stateDir);
245
+ const byId = new Map();
246
+ const dir = join(stateDir, INCIDENTS_DIR);
247
+ try {
248
+ if (existsSync(dir) && statSync(dir).isDirectory()) {
249
+ for (const name of readdirSync(dir)) {
250
+ if (!name.endsWith(".json"))
251
+ continue;
252
+ const path = join(dir, name);
253
+ try {
254
+ if (!statSync(path).isFile())
255
+ continue;
256
+ }
257
+ catch {
258
+ continue;
259
+ }
260
+ const stored = readIncidentFromPath(path);
261
+ if (stored)
262
+ byId.set(stored.eventId, stored);
263
+ }
264
+ }
265
+ }
266
+ catch (err) {
267
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
268
+ }
269
+ const legacy = readIncidentFromPath(legacyIncidentPath(stateDir));
270
+ if (legacy) {
271
+ const existing = byId.get(legacy.eventId);
272
+ if (!existing)
273
+ byId.set(legacy.eventId, legacy);
274
+ else if (legacy.closedPendingDelivery && !existing.closedPendingDelivery) {
275
+ byId.set(legacy.eventId, { ...existing, closedPendingDelivery: true });
276
+ }
277
+ }
278
+ return [...byId.values()];
279
+ }
280
+ function writeIncidentRecord(stateDir, record) {
281
+ writeJsonDurable(incidentEventPath(stateDir, record.eventId), record);
282
+ try {
283
+ const legacyPath = legacyIncidentPath(stateDir);
284
+ const existing = readIncidentFromPath(legacyPath);
285
+ if (existing && existing.eventId !== record.eventId && !legacyMigrationComplete(stateDir, existing)) {
286
+ process.stderr.write("verax: incident: legacy record retained\n");
287
+ return;
288
+ }
289
+ writeJsonDurable(legacyPath, record);
290
+ }
291
+ catch (err) {
292
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
293
+ }
294
+ }
295
+ function tryWriteIncidentRecord(stateDir, record) {
296
+ try {
297
+ writeIncidentRecord(stateDir, record);
298
+ return true;
299
+ }
300
+ catch (err) {
301
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
302
+ return false;
303
+ }
304
+ }
305
+ function tryRemoveIncidentRecord(stateDir, eventId) {
306
+ try {
307
+ rmSync(incidentEventPath(stateDir, eventId), { force: true });
308
+ }
309
+ catch (err) {
310
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
311
+ }
312
+ const legacy = readIncidentFromPath(legacyIncidentPath(stateDir));
313
+ if (legacy && legacy.eventId === eventId) {
314
+ try {
315
+ rmSync(legacyIncidentPath(stateDir), { force: true });
316
+ }
317
+ catch (err) {
318
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
319
+ }
320
+ }
321
+ }
322
+ function isUsableStoredEnvelope(envelope, eventId, publicKeyPem) {
323
+ const payload = envelope.payload;
324
+ if (!payload || typeof payload !== "object")
325
+ return false;
326
+ if (payload.eventId !== eventId)
327
+ return false;
328
+ if (typeof payload.triggerCode !== "string" || !isIntegrityReason(payload.triggerCode))
329
+ return false;
330
+ if (typeof envelope.sig !== "string" || envelope.sig === "")
331
+ return false;
332
+ try {
333
+ return verify(null, Buffer.from(canonical(payload), "utf8"), createPublicKey(publicKeyPem), Buffer.from(envelope.sig, "base64"));
334
+ }
335
+ catch {
336
+ return false;
337
+ }
338
+ }
339
+ function usableEnvelope(envelope, eventId, publicKeyPem) {
340
+ if (!envelope)
341
+ return undefined;
342
+ if (isUsableStoredEnvelope(envelope, eventId, publicKeyPem))
343
+ return envelope;
344
+ process.stderr.write("verax: incident: stored envelope rejected\n");
345
+ return undefined;
346
+ }
347
+ function incidentPayload(opts) {
348
+ return {
349
+ v: 1,
350
+ purpose: "verax.incident.v1",
351
+ eventId: opts.eventId,
352
+ observedAt: opts.observedAt,
353
+ triggerCode: opts.triggerCode,
354
+ scopeKind: "global",
355
+ enforcementState: "halted",
356
+ keyId: recordKeyId(opts.publicKeyPem),
357
+ ...(opts.memoryHead ? { memoryHead: opts.memoryHead } : {}),
358
+ };
359
+ }
360
+ function tryLoadRecordKeys(stateDir, keysDir) {
361
+ const resolved = resolveKeysDir(stateDir, keysDir ?? process.env.VERAX_KEYS_DIR);
362
+ try {
363
+ const recordSigner = {
364
+ publicKeyPem: readFileSync(join(resolved, "record.public.pem"), "utf8"),
365
+ privateKeyPem: readFileSync(join(resolved, "record.private.pem"), "utf8"),
366
+ };
367
+ const publicKeyPem = assertRecordKeyTrust({
368
+ stateDir,
369
+ keysDir: resolved,
370
+ recordSigner,
371
+ });
372
+ return { publicKeyPem, privateKeyPem: recordSigner.privateKeyPem };
373
+ }
374
+ catch {
375
+ return null;
376
+ }
377
+ }
378
+ function safeHasAlarmDelivery(stateDir, eventId) {
379
+ try {
380
+ return hasAlarmDelivery(stateDir, eventId);
381
+ }
382
+ catch (err) {
383
+ process.stderr.write(`verax: alarm-history: ${oneLine(err)}\n`);
384
+ return false;
385
+ }
386
+ }
387
+ function readHistoryIdentity(stateDir) {
388
+ const halt = readHalt(stateDir);
389
+ if (!halt.halted || halt.since?.via !== "integrity" || typeof halt.since.eventId !== "string")
390
+ return null;
391
+ if (!isAlarmEventId(halt.since.eventId)) {
392
+ process.stderr.write("verax: incident: history eventId rejected\n");
393
+ return null;
394
+ }
395
+ const trigger = halt.since.triggerCode ?? "";
396
+ if (!isIntegrityReason(trigger)) {
397
+ process.stderr.write("verax: incident: history triggerCode rejected\n");
398
+ return null;
399
+ }
400
+ return {
401
+ eventId: halt.since.eventId,
402
+ triggerCode: trigger,
403
+ observedAt: halt.since.atMs,
404
+ ...(halt.since.memoryHead ? { memoryHead: halt.since.memoryHead } : {}),
405
+ };
406
+ }
407
+ function recordForEvent(stateDir, eventId) {
408
+ return listIncidentRecords(stateDir).find((row) => row.eventId === eventId) ?? null;
409
+ }
410
+ function readIntegrityIdentity(stateDir) {
411
+ const halt = readHalt(stateDir);
412
+ if (!halt.halted)
413
+ return null;
414
+ const history = readHistoryIdentity(stateDir);
415
+ if (history) {
416
+ const record = recordForEvent(stateDir, history.eventId);
417
+ if (record)
418
+ return record;
419
+ return history;
420
+ }
421
+ // C1: switch with no history line — the on-disk record is this halt.
422
+ // An operator halt has `since` and does not own a leftover record.
423
+ const records = listIncidentRecords(stateDir).filter((row) => !row.closedPendingDelivery);
424
+ const record = records[0] ?? null;
425
+ if (record && (!halt.since || halt.since.via === "integrity"))
426
+ return record;
427
+ return null;
428
+ }
429
+ function persistEnvelope(stateDir, envelope) {
430
+ try {
431
+ writeAlarmOutbox(stateDir, envelope);
432
+ }
433
+ catch (err) {
434
+ process.stderr.write(`verax: alarm-outbox: ${oneLine(err)}\n`);
435
+ }
436
+ }
437
+ function signedEnvelope(opts, stored) {
438
+ return (usableEnvelope(stored.envelope, stored.eventId, opts.publicKeyPem) ??
439
+ signIncident(incidentPayload({
440
+ eventId: stored.eventId,
441
+ observedAt: stored.observedAt,
442
+ triggerCode: stored.triggerCode,
443
+ publicKeyPem: opts.publicKeyPem,
444
+ memoryHead: stored.memoryHead ?? opts.memoryHead,
445
+ }), opts.privateKeyPem));
446
+ }
447
+ function finishClosedPending(opts, stored) {
448
+ if (safeHasAlarmDelivery(opts.stateDir, stored.eventId)) {
449
+ tryRemoveIncidentRecord(opts.stateDir, stored.eventId);
450
+ return null;
451
+ }
452
+ if (!opts.alarmWebhookUrl)
453
+ return null;
454
+ if (hasAlarmOutbox(opts.stateDir, stored.eventId))
455
+ return null;
456
+ const envelope = signedEnvelope(opts, stored);
457
+ persistEnvelope(opts.stateDir, envelope);
458
+ if (hasAlarmOutbox(opts.stateDir, stored.eventId) || safeHasAlarmDelivery(opts.stateDir, stored.eventId)) {
459
+ tryRemoveIncidentRecord(opts.stateDir, stored.eventId);
460
+ }
461
+ return hasAlarmOutbox(opts.stateDir, stored.eventId) ? envelope : null;
462
+ }
463
+ function tryFinishClosedPending(opts, stored) {
464
+ try {
465
+ return finishClosedPending(opts, stored);
466
+ }
467
+ catch (err) {
468
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
469
+ return null;
470
+ }
471
+ }
472
+ function finishAllClosedPending(opts) {
473
+ let last = null;
474
+ for (const stored of listIncidentRecords(opts.stateDir)) {
475
+ if (!stored.closedPendingDelivery)
476
+ continue;
477
+ const envelope = tryFinishClosedPending(opts, stored);
478
+ if (envelope)
479
+ last = envelope;
480
+ }
481
+ return last;
482
+ }
483
+ /** Resume: same verify/re-sign path; pending marker is atomic or resume does not finish. */
484
+ export function closeIncidentsOnResume(stateDir, keysDir) {
485
+ migrateLegacyIncident(stateDir);
486
+ const keys = tryLoadRecordKeys(stateDir, keysDir);
487
+ const records = listIncidentRecords(stateDir);
488
+ const history = readHistoryIdentity(stateDir);
489
+ if (history && !records.some((row) => row.eventId === history.eventId))
490
+ records.push(history);
491
+ for (const stored of records) {
492
+ if (safeHasAlarmDelivery(stateDir, stored.eventId)) {
493
+ tryRemoveIncidentRecord(stateDir, stored.eventId);
494
+ continue;
495
+ }
496
+ let envelope;
497
+ if (keys) {
498
+ envelope = signedEnvelope(keys, stored);
499
+ persistEnvelope(stateDir, envelope);
500
+ }
501
+ else if (stored.envelope && typeof stored.envelope === "object") {
502
+ process.stderr.write("verax: incident: resume skipped unverified envelope\n");
503
+ }
504
+ if (hasAlarmOutbox(stateDir, stored.eventId) || safeHasAlarmDelivery(stateDir, stored.eventId)) {
505
+ tryRemoveIncidentRecord(stateDir, stored.eventId);
506
+ continue;
507
+ }
508
+ const pending = {
509
+ ...stored,
510
+ closedPendingDelivery: true,
511
+ ...(envelope ? { envelope } : {}),
512
+ };
513
+ writeIncidentRecord(stateDir, pending);
514
+ }
515
+ }
516
+ export function raiseMemoryIntegrityIncident(opts) {
517
+ let eventId = "";
518
+ let observedAt = opts.now ?? Date.now();
519
+ let triggerCode = opts.reason;
520
+ let memoryHead = opts.memoryHead;
521
+ let identity = null;
522
+ let wrote = false;
523
+ let abort = false;
524
+ let already = false;
525
+ try {
526
+ already = isHaltSwitchFile(opts.stateDir);
527
+ eventId = allocateIncidentEventId({
528
+ observedAt,
529
+ triggerCode,
530
+ publicKeyPem: opts.publicKeyPem,
531
+ });
532
+ migrateLegacyIncident(opts.stateDir);
533
+ finishAllClosedPending(opts);
534
+ const leftoverOpen = !already
535
+ ? (listIncidentRecords(opts.stateDir).find((row) => !row.closedPendingDelivery) ?? null)
536
+ : null;
537
+ identity = already ? readIntegrityIdentity(opts.stateDir) : leftoverOpen;
538
+ if (already && !identity) {
539
+ abort = true;
540
+ return null;
541
+ }
542
+ if (identity) {
543
+ eventId = identity.eventId;
544
+ observedAt = identity.observedAt;
545
+ triggerCode = identity.triggerCode;
546
+ memoryHead = identity.memoryHead ?? memoryHead;
547
+ }
548
+ const kept = usableEnvelope(identity?.envelope, eventId, opts.publicKeyPem);
549
+ const record = {
550
+ eventId,
551
+ triggerCode,
552
+ observedAt,
553
+ ...(memoryHead ? { memoryHead } : {}),
554
+ ...(kept ? { envelope: kept } : {}),
555
+ };
556
+ wrote = tryWriteIncidentRecord(opts.stateDir, record);
557
+ identity = { ...record };
558
+ }
559
+ catch (err) {
560
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
561
+ }
562
+ finally {
563
+ if (!already && !abort) {
564
+ try {
565
+ haltBody(opts.stateDir, INCIDENT_BY, "integrity", observedAt, undefined, {
566
+ ...(eventId !== "" ? { eventId } : {}),
567
+ triggerCode,
568
+ ...(memoryHead ? { memoryHead } : {}),
569
+ });
570
+ }
571
+ catch (err) {
572
+ process.stderr.write(`verax: halt: ${oneLine(err)}\n`);
573
+ if (!isHaltSwitchFile(opts.stateDir)) {
574
+ markHistoryUnavailable(opts.stateDir);
575
+ }
576
+ }
577
+ }
578
+ }
579
+ if (abort)
580
+ return null;
581
+ if (eventId === "")
582
+ return null;
583
+ if (!wrote && identity)
584
+ tryWriteIncidentRecord(opts.stateDir, identity);
585
+ try {
586
+ if (!opts.alarmWebhookUrl)
587
+ return null;
588
+ if (safeHasAlarmDelivery(opts.stateDir, eventId))
589
+ return null;
590
+ if (already && hasAlarmOutbox(opts.stateDir, eventId))
591
+ return null;
592
+ const envelope = usableEnvelope(identity?.envelope, eventId, opts.publicKeyPem) ??
593
+ signIncident(incidentPayload({ eventId, observedAt, triggerCode, publicKeyPem: opts.publicKeyPem, memoryHead }), opts.privateKeyPem);
594
+ if (identity && !identity.envelope) {
595
+ identity.envelope = envelope;
596
+ tryWriteIncidentRecord(opts.stateDir, identity);
597
+ }
598
+ persistEnvelope(opts.stateDir, envelope);
599
+ return already ? (hasAlarmOutbox(opts.stateDir, eventId) ? envelope : null) : envelope;
600
+ }
601
+ catch (err) {
602
+ process.stderr.write(`verax: incident: ${oneLine(err)}\n`);
603
+ return null;
604
+ }
605
+ }
606
+ /** On open: finish a missing halt, a missing outbox, or a resume-pending delivery. Same eventId. */
607
+ export function completeMemoryIntegrityIncident(opts) {
608
+ migrateLegacyIncident(opts.stateDir);
609
+ const pending = finishAllClosedPending(opts);
610
+ if (!isHaltSwitchFile(opts.stateDir)) {
611
+ const leftover = listIncidentRecords(opts.stateDir).find((row) => !row.closedPendingDelivery);
612
+ if (leftover) {
613
+ return raiseMemoryIntegrityIncident({
614
+ ...opts,
615
+ reason: leftover.triggerCode,
616
+ now: leftover.observedAt,
617
+ });
618
+ }
619
+ return pending;
620
+ }
621
+ const existing = readIntegrityIdentity(opts.stateDir);
622
+ return (raiseMemoryIntegrityIncident({
623
+ ...opts,
624
+ reason: existing?.triggerCode ?? "memory-integrity-mismatch",
625
+ now: existing?.observedAt,
626
+ }) ?? pending);
627
+ }
package/dist/keys.d.ts CHANGED
@@ -12,7 +12,24 @@ export declare class KeyAlgorithmError extends Error {
12
12
  }
13
13
  /** A public key this process will verify with. Anything but Ed25519 stops start. */
14
14
  export declare function assertEd25519PublicKey(pem: string, which: string): void;
15
- export declare function loadOrCreateSigners(stateDir: string): {
15
+ /** Keys live here. Default is `<stateDir>/keys`; `listen` / `createBodyServices` may pass `keysDir`. */
16
+ export declare function resolveKeysDir(stateDir: string, keysDir?: string | null): string;
17
+ /** Memory head lives here. `VERAX_MEMORY_HEAD_DIR` wins; otherwise the keys directory. */
18
+ export declare function resolveHeadDir(stateDir: string, keysDir?: string | null, headDir?: string | null): string;
19
+ /** Physical path for custody and head identity: junctions resolved, win32 case-folded. */
20
+ export declare function canonicalizeDirPath(dir: string): string;
21
+ /** True when `inner` is `root` or a path under it. */
22
+ export declare function pathIsInsideDir(root: string, inner: string): boolean;
23
+ export declare function loadOrCreateSigners(stateDir: string, keysDir?: string | null): {
16
24
  recordSigner: KeyPair;
17
25
  effectSigner: KeyPair;
18
26
  };
27
+ /**
28
+ * Record public/private match plus `VERAX_RECORD_PUBKEY_PIN` (PEM).
29
+ * Body open, rehead, and reattest call this before any head write.
30
+ */
31
+ export declare function assertRecordKeyTrust(opts: {
32
+ stateDir: string;
33
+ keysDir?: string;
34
+ recordSigner: KeyPair;
35
+ }): string;