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