@mcpose/audit 2.0.2 → 3.0.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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +437 -28
  3. package/dist/chain.d.ts +55 -0
  4. package/dist/chain.d.ts.map +1 -0
  5. package/dist/chain.js +265 -0
  6. package/dist/chain.js.map +1 -0
  7. package/dist/index.d.ts +9 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +7 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/middleware.d.ts +5 -0
  12. package/dist/middleware.d.ts.map +1 -0
  13. package/dist/middleware.js +488 -0
  14. package/dist/middleware.js.map +1 -0
  15. package/dist/sensitivity.d.ts +12 -0
  16. package/dist/sensitivity.d.ts.map +1 -0
  17. package/dist/sensitivity.js +24 -0
  18. package/dist/sensitivity.js.map +1 -0
  19. package/dist/signingKey.d.ts +11 -0
  20. package/dist/signingKey.d.ts.map +1 -0
  21. package/dist/signingKey.js +30 -0
  22. package/dist/signingKey.js.map +1 -0
  23. package/dist/subjectKeyStore.d.ts +17 -0
  24. package/dist/subjectKeyStore.d.ts.map +1 -0
  25. package/dist/subjectKeyStore.js +37 -0
  26. package/dist/subjectKeyStore.js.map +1 -0
  27. package/dist/types.d.ts +244 -0
  28. package/dist/types.d.ts.map +1 -0
  29. package/dist/types.js +2 -0
  30. package/dist/types.js.map +1 -0
  31. package/dist/verify.d.ts +24 -0
  32. package/dist/verify.d.ts.map +1 -0
  33. package/dist/verify.js +50 -0
  34. package/dist/verify.js.map +1 -0
  35. package/package.json +43 -14
  36. package/src/__tests__/chain.batch.test.ts +30 -0
  37. package/src/__tests__/chain.test.ts +399 -0
  38. package/src/__tests__/erasable.test.ts +499 -0
  39. package/src/__tests__/merkle-batch.middleware.test.ts +96 -0
  40. package/src/__tests__/middleware.http.test.ts +172 -0
  41. package/src/__tests__/middleware.robustness.test.ts +737 -0
  42. package/src/__tests__/middleware.test.ts +1121 -0
  43. package/src/__tests__/properties.test.ts +737 -0
  44. package/src/__tests__/sensitivity.test.ts +72 -0
  45. package/src/__tests__/signingKey.test.ts +76 -0
  46. package/src/chain.ts +317 -0
  47. package/src/index.ts +31 -0
  48. package/src/middleware.ts +690 -0
  49. package/src/sensitivity.ts +33 -0
  50. package/src/signingKey.ts +35 -0
  51. package/src/subjectKeyStore.ts +38 -0
  52. package/src/types.ts +281 -0
  53. package/src/verify.ts +76 -0
@@ -0,0 +1,690 @@
1
+ import { createCipheriv, randomBytes, createHmac } from 'node:crypto';
2
+ import type {
3
+ AuditEvent,
4
+ AuditMiddlewareHandle,
5
+ AuditOptions,
6
+ ReplayManifest,
7
+ SensitivityTier,
8
+ } from './types.js';
9
+ import {
10
+ canonicalJson,
11
+ chainPreimageFields,
12
+ computeChainHash,
13
+ computeMerkleRootAndProofs,
14
+ sha256hex,
15
+ stableStringify,
16
+ } from './chain.js';
17
+ import { hasToolContent, markPassThroughObserver } from 'mcpose';
18
+ import type {
19
+ Identity,
20
+ ProxyContext,
21
+ ProxyIdentity,
22
+ RejectionReason,
23
+ } from 'mcpose';
24
+
25
+ /**
26
+ * What the audit layer needs from an audited request. Tool calls and prompt
27
+ * fetches both expose a name and optional arguments, which is why one
28
+ * implementation can serve both.
29
+ */
30
+ interface AuditableRequest {
31
+ params: { name: string; arguments?: Record<string, unknown> | undefined };
32
+ }
33
+
34
+ // Domain-separation labels for subkey derivation. The version segment lets the
35
+ // derivation scheme rotate without colliding with chains written under an old
36
+ // scheme. v1 → v2: canonical-JSON preimages, signed full manifest,
37
+ // domain-separated Merkle, per-position event keys, AEAD-bound ciphertexts.
38
+ // See ADR-0003 and ADR-0004.
39
+ const DOMAIN_CHAIN = Buffer.from('mcpose/v2/chain');
40
+ const DOMAIN_ENC = Buffer.from('mcpose/v2/enc');
41
+ const DOMAIN_MANIFEST = 'mcpose/v2/manifest';
42
+ const DOMAIN_EVENT_KEY = 'mcpose/v2/eventkey\0';
43
+ const DOMAIN_AAD = 'mcpose/v2/aad\0';
44
+ // Erasable mode only (ADR-0018): keys the payload hashes so that destroying a
45
+ // subject key destroys confirmability along with decryptability. A new label
46
+ // for a new mechanism is additive within v2 — no existing label changes, and
47
+ // no default-mode event is derived under it.
48
+ const DOMAIN_HASH_KEY = 'mcpose/v2/hashkey';
49
+
50
+ interface SessionState {
51
+ events: AuditEvent[];
52
+ prevChainHash: string;
53
+ startedAt: string;
54
+ identity: Identity;
55
+ proxy: ProxyIdentity;
56
+ /**
57
+ * Calls admitted to this session whose event is not yet appended and
58
+ * persisted, keyed by a per-call token. `closeSession` drains this before
59
+ * sealing, so a call that is still awaiting the upstream when the session
60
+ * is torn down (client DELETE, TTL expiry, shutdown) lands in the manifest
61
+ * instead of emitting an orphan at position 0 (#168). The value names the
62
+ * call so a drain that times out can report each straggler.
63
+ */
64
+ inflight: Map<symbol, { tool: string; requestId: string }>;
65
+ /** Resolves the pending drain wait once `inflight` empties. */
66
+ onDrained?: () => void;
67
+ /**
68
+ * The in-progress close, so concurrent `closeSession` calls share one
69
+ * drain, one signature, and one manifest.
70
+ */
71
+ closing?: Promise<ReplayManifest | undefined>;
72
+ }
73
+
74
+ /**
75
+ * A session that has been drained and removed from admission but whose
76
+ * manifest is not yet delivered (#169). The unsigned manifest is fixed at
77
+ * seal time, so every retry signs and delivers the same bytes; the signature
78
+ * is kept once obtained, so a sink failure never triggers a second signing.
79
+ */
80
+ interface SealedSession {
81
+ unsigned: Omit<ReplayManifest, 'signature'>;
82
+ signature?: string;
83
+ /** The in-progress sign-and-deliver attempt, shared by concurrent retries. */
84
+ attempt?: Promise<ReplayManifest>;
85
+ }
86
+
87
+ function aesEncrypt(plaintext: string, key: Buffer, aad: string): string {
88
+ if (key.length !== 32) {
89
+ throw new RangeError(
90
+ `aesEncrypt: expected a 32-byte key, got ${key.length}`,
91
+ );
92
+ }
93
+ const iv = randomBytes(12);
94
+ const cipher = createCipheriv('aes-256-gcm', key, iv);
95
+ cipher.setAAD(Buffer.from(aad));
96
+ const encrypted = Buffer.concat([
97
+ cipher.update(plaintext, 'utf8'),
98
+ cipher.final(),
99
+ ]);
100
+ const tag = cipher.getAuthTag();
101
+ return Buffer.concat([iv, tag, encrypted]).toString('base64');
102
+ }
103
+
104
+ /**
105
+ * Per-event AES key. Bound to session + position + event id so no two
106
+ * events can share a key even if a host reuses a ProxyContext (and with it
107
+ * a requestId) across calls.
108
+ */
109
+ function deriveEventKey(
110
+ encRoot: Buffer,
111
+ sessionId: string | undefined,
112
+ position: number,
113
+ eventId: string,
114
+ ): Buffer {
115
+ return createHmac('sha256', encRoot)
116
+ .update(`${DOMAIN_EVENT_KEY}${sessionId ?? ''}\0${position}\0${eventId}`)
117
+ .digest();
118
+ }
119
+
120
+ /**
121
+ * Payload hash for one event.
122
+ *
123
+ * Default mode: plain `sha256`, unchanged and unkeyed, so a replay verifier
124
+ * needs no key custody. Erasable mode: `HMAC-SHA256` under a subkey of the
125
+ * subject key, so an adversary holding a candidate payload cannot confirm it
126
+ * against an erased event's hash (ADR-0018). Both hash the same
127
+ * `stableStringify` bytes, so only the key changes.
128
+ */
129
+ function payloadHash(value: unknown, hashSubkey: Buffer | undefined): string {
130
+ const serialized = stableStringify(value);
131
+ return hashSubkey === undefined
132
+ ? sha256hex(serialized)
133
+ : createHmac('sha256', hashSubkey).update(serialized).digest('hex');
134
+ }
135
+
136
+ function anonymousIdentity(): Identity {
137
+ return {
138
+ sub: 'anonymous',
139
+ type: 'service',
140
+ roles: [],
141
+ claims: {},
142
+ resolvedAt: new Date().toISOString(),
143
+ source: 'custom',
144
+ };
145
+ }
146
+
147
+ function getRejectionReason(err: unknown): RejectionReason | undefined {
148
+ const data = (err as { data?: { rejectionReason?: unknown } } | null)?.data;
149
+ return typeof data?.rejectionReason === 'string'
150
+ ? (data.rejectionReason as RejectionReason)
151
+ : undefined;
152
+ }
153
+
154
+ export function createAuditMiddleware(
155
+ options: AuditOptions,
156
+ ): AuditMiddlewareHandle {
157
+ const sessions = new Map<string, SessionState>();
158
+ // Drained sessions awaiting signature or delivery, retried by closeSession.
159
+ const sealed = new Map<string, SealedSession>();
160
+ const includeRejections = options.includeRejections ?? true;
161
+ const closeDrainTimeoutMs = options.closeDrainTimeoutMs ?? 30_000;
162
+ const reportAuditError: NonNullable<AuditOptions['onAuditError']> =
163
+ options.onAuditError ?? ((err) => console.error(err));
164
+ // A throwing reporter is outside the audited call path too (#172): it must
165
+ // not replace a tool result, mask an upstream error, or abort a drain.
166
+ const onAuditError: NonNullable<AuditOptions['onAuditError']> = (
167
+ err,
168
+ info,
169
+ ) => {
170
+ try {
171
+ reportAuditError(err, info);
172
+ } catch {
173
+ // Nothing left to report it to.
174
+ }
175
+ };
176
+
177
+ // Private subkeys, derived once from the signing secret THROUGH the oracle with
178
+ // domain separation. The provider never exposes raw key bytes, and keyId must
179
+ // NOT be used as key material — keyId is a public identifier, published in
180
+ // ReplayManifest.signedBy. sign() is HMAC-SHA256 per the SigningKeyProvider
181
+ // contract, hence a PRF suitable for key derivation.
182
+ // chainKey — keys the per-entry HMAC chain (forgery resistance)
183
+ // encRoot — root for per-event AES-256 keys (high-tier confidentiality)
184
+ // Cache the promise so concurrent first calls share one derivation; a failed
185
+ // derivation clears the cache so a transient provider error is retryable.
186
+ let subkeys: Promise<{ chainKey: Buffer; encRoot: Buffer }> | undefined;
187
+ const deriveSubkeys = () => {
188
+ subkeys ??= (async () => {
189
+ const [chainKey, encRoot] = await Promise.all([
190
+ options.signingKey.sign(DOMAIN_CHAIN),
191
+ options.signingKey.sign(DOMAIN_ENC),
192
+ ]);
193
+ return { chainKey, encRoot };
194
+ })();
195
+ subkeys.catch(() => {
196
+ subkeys = undefined;
197
+ });
198
+ return subkeys;
199
+ };
200
+
201
+ // One implementation for both audited surfaces. A tool call and a prompt
202
+ // fetch differ only in the event's `kind`: both requests carry a name and
203
+ // optional arguments, and both share the session chain, so duplicating the
204
+ // body would duplicate every invariant below with it (ADR-0014).
205
+ const observe = async <Req extends AuditableRequest, Res>(
206
+ kind: 'prompt' | undefined,
207
+ req: Req,
208
+ next: (req: Req) => Promise<Res>,
209
+ ctx: ProxyContext,
210
+ isInBandError?: (result: Res) => boolean,
211
+ ): Promise<Res> => {
212
+ // The proxy identity is a required covered field (ADR-0019), so a context
213
+ // without one cannot produce a verifiable event. That is a configuration
214
+ // error rather than a runtime condition: core has stamped `ctx.proxy` on
215
+ // every ProxyContext since 3.0.0, so reaching here without it means a host
216
+ // invoked this middleware with a hand-built context.
217
+ //
218
+ // Handled here, at the pre-call stage alongside subkey derivation, which is
219
+ // the one failure point allowed to fail the call. Throwing after the call
220
+ // would mask the tool result, and substituting a sentinel identity would
221
+ // write a trail that looks attributed and is not, which is the failure
222
+ // #85 and #122 exist to prevent.
223
+ const proxy = ctx.proxy;
224
+ if (proxy === undefined) {
225
+ throw new Error(
226
+ 'mcpose/audit: ctx.proxy is required, because the proxy identity is a covered field of every audit event. mcpose core stamps it on every ProxyContext; a host invoking this middleware with its own context must supply it.',
227
+ );
228
+ }
229
+ const identity = ctx.identity ?? anonymousIdentity();
230
+ const sessionId = ctx.sessionId;
231
+ const tool = req.params.name;
232
+ const args = (req.params.arguments as Record<string, unknown>) ?? {};
233
+
234
+ if (sessionId && !sessions.has(sessionId)) {
235
+ // First-seen wins: the manifest records the proxy identity of the
236
+ // request that opened the session, and each event still records its own.
237
+ // No backfill branch is needed now that `proxy` is always present.
238
+ sessions.set(sessionId, {
239
+ events: [],
240
+ prevChainHash: '',
241
+ startedAt: new Date().toISOString(),
242
+ identity,
243
+ proxy,
244
+ inflight: new Map(),
245
+ });
246
+ }
247
+ // Admission (#168): registered synchronously, before the first await of
248
+ // this function, and captured once. From here until the `finally` below
249
+ // the call counts as in flight: `closeSession` drains that set before it
250
+ // seals, so the session cannot vanish under a call that is still deriving
251
+ // keys, awaiting the upstream, or persisting its event. Re-resolving the
252
+ // id after an await is what produced position-0 orphans with no manifest.
253
+ const session = sessionId ? sessions.get(sessionId) : undefined;
254
+ const admission = Symbol(tool);
255
+ session?.inflight.set(admission, { tool, requestId: ctx.requestId });
256
+
257
+ try {
258
+ // Subkey derivation runs BEFORE the upstream call: if the signing
259
+ // provider is unavailable the call fails fast rather than running
260
+ // unaudited.
261
+ const { chainKey, encRoot } = await deriveSubkeys();
262
+ // Erasable mode (ADR-0018). Fetched at the pre-call stage alongside subkey
263
+ // derivation, for the same reason: without the subject key there is no way
264
+ // to record this event, so the call fails fast rather than running
265
+ // unaudited. Nothing is cached across calls — `destroy` must take effect
266
+ // immediately, and a subject that calls again after erasure gets a fresh
267
+ // key from the store rather than a stale one from here. A rejected fetch
268
+ // therefore leaves no poisoned state and the next call retries.
269
+ //
270
+ // The subject is the RESOLVED identity's `sub`, so anonymous events all
271
+ // land in the `anonymousIdentity()` bucket, which is the designated
272
+ // single bucket the ADR calls for.
273
+ // Written as a ternary rather than `await options.keyStore?.…` so default
274
+ // mode does not even take the extra microtask tick an `await undefined`
275
+ // would cost it.
276
+ const subjectKey = options.keyStore
277
+ ? await options.keyStore.getOrCreate(identity.sub)
278
+ : undefined;
279
+ const startedAt = new Date().toISOString();
280
+ const start = performance.now();
281
+
282
+ let result: unknown;
283
+ let thrown: unknown;
284
+ let threw = false;
285
+ try {
286
+ result = await next(req);
287
+ } catch (err) {
288
+ thrown = err;
289
+ threw = true;
290
+ }
291
+
292
+ // Post-call audit section. Two invariants:
293
+ // 1. Atomic append — no `await` between reading the position and
294
+ // pushing the event, so concurrent calls in one session cannot
295
+ // allocate duplicate positions (buildEvent is fully synchronous).
296
+ // 2. Never throws — an audit failure is reported via onAuditError and
297
+ // must not fail (or mask the failure of) the audited call itself.
298
+ try {
299
+ const rejectionReason = threw ? getRejectionReason(thrown) : undefined;
300
+ // A call can fail without throwing: an MCP tool reports failure
301
+ // in-band with `isError: true` (#171). The caller supplies the
302
+ // predicate, so only tool calls pass one and prompts never match.
303
+ const inBandError = !threw && isInBandError?.(result as Res) === true;
304
+ const outcome: AuditEvent['outcome'] =
305
+ rejectionReason !== undefined
306
+ ? 'rejected'
307
+ : threw || inBandError
308
+ ? 'error'
309
+ : 'success';
310
+
311
+ if (outcome !== 'rejected' || includeRejections) {
312
+ let tier: SensitivityTier;
313
+ try {
314
+ tier = options.sensitivityResolver(tool, identity, args);
315
+ } catch (err) {
316
+ onAuditError(err, {
317
+ tool,
318
+ requestId: ctx.requestId,
319
+ ...(sessionId === undefined ? {} : { sessionId }),
320
+ });
321
+ tier = 'high';
322
+ }
323
+
324
+ const position = session?.events.length ?? 0;
325
+ const event = buildEvent({
326
+ ctx,
327
+ identity,
328
+ proxy,
329
+ kind,
330
+ tool,
331
+ args,
332
+ result: threw ? undefined : result,
333
+ startedAt,
334
+ endedAt: new Date().toISOString(),
335
+ duration_ms: Math.round(performance.now() - start),
336
+ outcome,
337
+ rejectionReason,
338
+ error:
339
+ outcome !== 'error'
340
+ ? undefined
341
+ : threw
342
+ ? {
343
+ name: thrown instanceof Error ? thrown.name : 'Error',
344
+ message:
345
+ thrown instanceof Error
346
+ ? thrown.message
347
+ : String(thrown),
348
+ }
349
+ : // A fixed message: `error` is never encrypted, so copying the
350
+ // tool's own text here would leak a high-tier payload.
351
+ {
352
+ name: 'ToolError',
353
+ message: 'Tool result returned isError: true',
354
+ },
355
+ position,
356
+ prevChainHash: session?.prevChainHash ?? '',
357
+ tier,
358
+ chainKey,
359
+ encRoot,
360
+ subjectKey,
361
+ });
362
+ if (session) {
363
+ session.events.push(event);
364
+ session.prevChainHash = event.chainHash;
365
+ }
366
+ await options.onEvent(event);
367
+ }
368
+ } catch (err) {
369
+ onAuditError(err, {
370
+ tool,
371
+ requestId: ctx.requestId,
372
+ ...(sessionId === undefined ? {} : { sessionId }),
373
+ });
374
+ }
375
+
376
+ if (threw) throw thrown;
377
+ return result as Awaited<ReturnType<typeof next>>;
378
+ } finally {
379
+ // Settle after the event is appended and `onEvent` has settled, so a
380
+ // draining close also waits for pending persistence. A pre-call failure
381
+ // lands here too, so a rejected key fetch never leaves the session
382
+ // looking busy.
383
+ if (session) {
384
+ session.inflight.delete(admission);
385
+ if (session.inflight.size === 0) session.onDrained?.();
386
+ }
387
+ }
388
+ };
389
+
390
+ // Tool calls: wrapped so `passThroughTools` stay audited. Prompts have no
391
+ // pass-through concept, so the prompt middleware needs no wrapper.
392
+ const inner: AuditMiddlewareHandle['middleware'] = (req, next, ctx) =>
393
+ observe(
394
+ undefined,
395
+ req,
396
+ next,
397
+ ctx,
398
+ (result) => hasToolContent(result) && result.isError === true,
399
+ );
400
+ const middleware = markPassThroughObserver(inner);
401
+ const promptMiddleware: AuditMiddlewareHandle['promptMiddleware'] = (
402
+ req,
403
+ next,
404
+ ctx,
405
+ ) => observe('prompt', req, next, ctx);
406
+
407
+ const closeSession: AuditMiddlewareHandle['closeSession'] = (sessionId) => {
408
+ const session = sessions.get(sessionId);
409
+ if (session) {
410
+ // A close already in progress is the close: joining it is what keeps a
411
+ // DELETE that races a TTL expiry from signing two manifests.
412
+ session.closing ??= sealSession(sessionId, session);
413
+ return session.closing;
414
+ }
415
+ // Sealed but undelivered: a signer or sink failed on an earlier close.
416
+ // Retry from where it stopped instead of reporting the session unknown.
417
+ const pending = sealed.get(sessionId);
418
+ if (pending) return finalize(sessionId, pending);
419
+ return Promise.resolve(undefined);
420
+ };
421
+
422
+ const sealSession = async (
423
+ sessionId: string,
424
+ session: SessionState,
425
+ ): Promise<ReplayManifest | undefined> => {
426
+ // Drain: every admitted call appends its event before it settles, so the
427
+ // manifest sealed below covers them all with continuous positions. The
428
+ // loop re-checks because a call can be admitted while one drain waits.
429
+ // Bounded, because a handler or sink that never settles must not hold
430
+ // the session's already-recorded events unsigned forever: past the
431
+ // deadline the manifest seals what it has and each straggler is reported.
432
+ const deadline = performance.now() + closeDrainTimeoutMs;
433
+ while (session.inflight.size > 0) {
434
+ const remaining = deadline - performance.now();
435
+ if (remaining <= 0) {
436
+ for (const { tool, requestId } of session.inflight.values()) {
437
+ onAuditError(
438
+ new Error(
439
+ `mcpose/audit: closeSession(${sessionId}) sealed after ${closeDrainTimeoutMs} ms with this call still in flight; its event is not in the manifest`,
440
+ ),
441
+ { tool, requestId, sessionId },
442
+ );
443
+ }
444
+ break;
445
+ }
446
+ await new Promise<void>((resolve) => {
447
+ const timer = Number.isFinite(remaining)
448
+ ? setTimeout(resolve, remaining)
449
+ : undefined;
450
+ session.onDrained = () => {
451
+ if (timer !== undefined) clearTimeout(timer);
452
+ resolve();
453
+ };
454
+ });
455
+ }
456
+ delete session.onDrained;
457
+ // Sealed: the session leaves the admission map here, so no later call can
458
+ // append to a manifest that is already being signed. What follows can
459
+ // still fail, so the sealed state is kept until delivery succeeds (#169).
460
+ sessions.delete(sessionId);
461
+ if (session.events.length === 0) return undefined;
462
+
463
+ const hashes = session.events.map((e) => e.chainHash);
464
+ const { merkleRoot, merkleProofs } = computeMerkleRootAndProofs(hashes);
465
+
466
+ // The signature covers the ENTIRE manifest (domain-separated, canonical
467
+ // serialization) — signing only the Merkle root would leave sessionId,
468
+ // identity, eventCount, and the proofs swappable after the fact.
469
+ const unsigned: Omit<ReplayManifest, 'signature'> = {
470
+ sessionId,
471
+ identity: session.identity,
472
+ proxy: session.proxy,
473
+ startedAt: session.startedAt,
474
+ closedAt: new Date().toISOString(),
475
+ eventCount: session.events.length,
476
+ merkleRoot,
477
+ merkleProofs,
478
+ signedBy: options.signingKey.keyId,
479
+ };
480
+ const previous = sealed.get(sessionId);
481
+ if (previous) {
482
+ // The id was reused before the earlier session's manifest was delivered.
483
+ // The host had every chance to retry; keeping the newer one is the only
484
+ // choice that does not lose the session that is closing now.
485
+ onAuditError(
486
+ new Error(
487
+ `mcpose/audit: closeSession(${sessionId}) replaced an undelivered manifest for an earlier session with the same id`,
488
+ ),
489
+ { tool: '', requestId: '', sessionId },
490
+ );
491
+ }
492
+ const pending: SealedSession = { unsigned };
493
+ sealed.set(sessionId, pending);
494
+ return finalize(sessionId, pending);
495
+ };
496
+
497
+ /**
498
+ * Signs and delivers a sealed manifest. Each step is memoized on the sealed
499
+ * state, so a retry after a transient signer failure signs the same payload
500
+ * (same `closedAt`, so the same bytes) and a retry after a sink failure
501
+ * re-delivers the identical signed manifest rather than minting a second
502
+ * one. Concurrent retries share one attempt.
503
+ */
504
+ const finalize = (
505
+ sessionId: string,
506
+ pending: SealedSession,
507
+ ): Promise<ReplayManifest> => {
508
+ pending.attempt ??= (async () => {
509
+ try {
510
+ if (pending.signature === undefined) {
511
+ const payload = canonicalJson({
512
+ domain: DOMAIN_MANIFEST,
513
+ manifest: pending.unsigned,
514
+ });
515
+ pending.signature = (
516
+ await options.signingKey.sign(Buffer.from(payload))
517
+ ).toString('hex');
518
+ }
519
+ const manifest: ReplayManifest = {
520
+ ...pending.unsigned,
521
+ signature: pending.signature,
522
+ };
523
+ await options.onManifest?.(manifest);
524
+ sealed.delete(sessionId);
525
+ return manifest;
526
+ } finally {
527
+ delete pending.attempt;
528
+ }
529
+ })();
530
+ return pending.attempt;
531
+ };
532
+
533
+ return { middleware, promptMiddleware, closeSession };
534
+ }
535
+
536
+ /** Rebuilds the exact signed payload for a manifest (used by verifiers). */
537
+ export function manifestSigningPayload(
538
+ manifest: Omit<ReplayManifest, 'signature'>,
539
+ ): string {
540
+ const {
541
+ sessionId,
542
+ identity,
543
+ proxy,
544
+ startedAt,
545
+ closedAt,
546
+ eventCount,
547
+ merkleRoot,
548
+ merkleProofs,
549
+ signedBy,
550
+ } = manifest;
551
+ return canonicalJson({
552
+ domain: DOMAIN_MANIFEST,
553
+ manifest: {
554
+ sessionId,
555
+ identity,
556
+ // Required covered field, included unconditionally (ADR-0019). Under
557
+ // the omission pattern a manifest with `proxy` stripped rebuilt the
558
+ // same payload as one that never had it, so the signature could not
559
+ // detect the removal.
560
+ proxy,
561
+ startedAt,
562
+ closedAt,
563
+ eventCount,
564
+ merkleRoot,
565
+ merkleProofs,
566
+ signedBy,
567
+ },
568
+ });
569
+ }
570
+
571
+ // ── Helpers ────────────────────────────────────────────────────────────────────
572
+
573
+ interface BuildParams {
574
+ ctx: ProxyContext;
575
+ identity: Identity;
576
+ /**
577
+ * Narrowed from `ctx.proxy` by the pre-call guard, so this stays total and
578
+ * the required covered field cannot be re-widened here (ADR-0019).
579
+ */
580
+ proxy: ProxyIdentity;
581
+ /** `'prompt'` for a prompts/get event; undefined for a tool call. */
582
+ kind: 'prompt' | undefined;
583
+ tool: string;
584
+ args: Record<string, unknown>;
585
+ result: unknown;
586
+ startedAt: string;
587
+ endedAt: string;
588
+ duration_ms: number;
589
+ outcome: AuditEvent['outcome'];
590
+ rejectionReason: RejectionReason | undefined;
591
+ error: { name: string; message: string } | undefined;
592
+ position: number;
593
+ prevChainHash: string;
594
+ tier: SensitivityTier;
595
+ chainKey: Buffer;
596
+ encRoot: Buffer;
597
+ /**
598
+ * The subject's destroyable key in erasable mode, `undefined` in default
599
+ * mode. Its presence is the ONLY thing that changes derivation, which is
600
+ * what keeps default mode byte-identical (ADR-0018).
601
+ */
602
+ subjectKey: Buffer | undefined;
603
+ }
604
+
605
+ /** Fully synchronous — position allocation relies on that (no await between read and append). */
606
+ function buildEvent(p: BuildParams): AuditEvent {
607
+ // Fail CLOSED: only explicit low/medium get plaintext; any other tier
608
+ // value — including garbage from a user-supplied resolver — encrypts.
609
+ // Decided before the preimage is built, because the tier is a covered
610
+ // field and must be the one the event actually ships with (ADR-0015).
611
+ const sensitivityTier =
612
+ p.tier === 'low' || p.tier === 'medium' ? p.tier : 'high';
613
+
614
+ // Erasable mode: one subkey off the subject key keys both payload hashes.
615
+ // Derived per event rather than held anywhere, so it dies with the subject
616
+ // key it came from (ADR-0018).
617
+ const hashSubkey =
618
+ p.subjectKey === undefined
619
+ ? undefined
620
+ : createHmac('sha256', p.subjectKey).update(DOMAIN_HASH_KEY).digest();
621
+
622
+ const withoutChainHash = {
623
+ id: p.ctx.requestId,
624
+ startedAt: p.startedAt,
625
+ endedAt: p.endedAt,
626
+ ...(p.ctx.sessionId !== undefined ? { sessionId: p.ctx.sessionId } : {}),
627
+ ...(p.ctx.delegatedFrom !== undefined
628
+ ? { delegatedFrom: p.ctx.delegatedFrom }
629
+ : {}),
630
+ proxy: p.proxy,
631
+ ...(p.kind !== undefined ? { kind: p.kind } : {}),
632
+ // Optional covered field under the ADR-0012 omission rule, exactly as
633
+ // `kind` is: default-mode events do not carry the key at all, so their
634
+ // preimage is unchanged (ADR-0018).
635
+ ...(p.subjectKey !== undefined ? { erasable: true as const } : {}),
636
+ identity: p.identity,
637
+ tool: p.tool,
638
+ duration_ms: p.duration_ms,
639
+ outcome: p.outcome,
640
+ sensitivityTier,
641
+ ...(p.rejectionReason !== undefined
642
+ ? { rejectionReason: p.rejectionReason }
643
+ : {}),
644
+ ...(p.error !== undefined ? { error: p.error } : {}),
645
+ inputHash: payloadHash(p.args, hashSubkey),
646
+ outputHash: payloadHash(p.result ?? null, hashSubkey),
647
+ replayManifestPosition: p.position,
648
+ };
649
+
650
+ const chainHash = computeChainHash(
651
+ chainPreimageFields(withoutChainHash as Omit<AuditEvent, 'chainHash'>),
652
+ p.prevChainHash,
653
+ p.chainKey,
654
+ );
655
+
656
+ const base = { ...withoutChainHash, chainHash };
657
+
658
+ if (sensitivityTier !== 'high') {
659
+ return {
660
+ ...base,
661
+ sensitivityTier,
662
+ inputRaw: p.args,
663
+ outputRaw: p.result,
664
+ };
665
+ }
666
+ // Erasable mode swaps the ROOT and nothing else: same label, same session,
667
+ // position and event-id inputs, same AES-256-GCM layout and AAD. Only the
668
+ // key's provenance changes, from the pure-derived `encRoot` to the stored,
669
+ // destroyable subject key (ADR-0018).
670
+ const eventKey = deriveEventKey(
671
+ p.subjectKey ?? p.encRoot,
672
+ p.ctx.sessionId,
673
+ p.position,
674
+ base.id,
675
+ );
676
+ return {
677
+ ...base,
678
+ sensitivityTier: 'high',
679
+ inputEncrypted: aesEncrypt(
680
+ stableStringify(p.args),
681
+ eventKey,
682
+ `${DOMAIN_AAD}${base.id}\0input`,
683
+ ),
684
+ outputEncrypted: aesEncrypt(
685
+ stableStringify(p.result ?? null),
686
+ eventKey,
687
+ `${DOMAIN_AAD}${base.id}\0output`,
688
+ ),
689
+ };
690
+ }