@kya-os/mcp-i-runtime 1.0.0 → 1.2.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 (57) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/config.d.ts +5 -7
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js +4 -6
  5. package/dist/config.js.map +1 -1
  6. package/dist/index.d.ts +4 -2
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +16 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/runtime/audit-logger.d.ts +6 -28
  11. package/dist/runtime/audit-logger.d.ts.map +1 -1
  12. package/dist/runtime/audit-logger.js +5 -3
  13. package/dist/runtime/audit-logger.js.map +1 -1
  14. package/dist/runtime/audit.d.ts +132 -0
  15. package/dist/runtime/audit.d.ts.map +1 -0
  16. package/dist/runtime/audit.js +424 -0
  17. package/dist/runtime/audit.js.map +1 -0
  18. package/dist/runtime/base.d.ts +9 -48
  19. package/dist/runtime/base.d.ts.map +1 -1
  20. package/dist/runtime/base.js +109 -89
  21. package/dist/runtime/base.js.map +1 -1
  22. package/dist/runtime/needs-authorization.d.ts +33 -0
  23. package/dist/runtime/needs-authorization.d.ts.map +1 -0
  24. package/dist/runtime/needs-authorization.js +43 -0
  25. package/dist/runtime/needs-authorization.js.map +1 -0
  26. package/dist/services/oauth-config.service.d.ts.map +1 -1
  27. package/dist/services/oauth-config.service.js +29 -0
  28. package/dist/services/oauth-config.service.js.map +1 -1
  29. package/package.json +7 -3
  30. package/src/__tests__/config/provider-runtime-config.test.ts +2 -9
  31. package/src/__tests__/config.test.ts +12 -11
  32. package/src/__tests__/integration/full-flow.test.ts +0 -5
  33. package/src/__tests__/integration.test.ts +2 -6
  34. package/src/__tests__/runtime/audit.test.ts +327 -0
  35. package/src/__tests__/runtime/base-extensions.test.ts +0 -46
  36. package/src/__tests__/runtime/base.test.ts +71 -102
  37. package/src/__tests__/runtime/delegation-flow.test.ts +0 -4
  38. package/src/__tests__/runtime/process-tool-call-security.test.ts +5 -11
  39. package/src/__tests__/runtime/proof-client-did.test.ts +0 -4
  40. package/src/__tests__/runtime/provider-selection.test.ts +0 -2
  41. package/src/__tests__/runtime/route-interception.test.ts +7 -4
  42. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +23 -31
  43. package/src/__tests__/services/tool-protection-merged-config.test.ts +0 -40
  44. package/src/config/__tests__/merged-config.spec.ts +0 -26
  45. package/src/config.ts +9 -10
  46. package/src/index.ts +30 -5
  47. package/src/runtime/__tests__/audit-logger-compat.test.ts +15 -0
  48. package/src/runtime/__tests__/needs-authorization.test.ts +41 -0
  49. package/src/runtime/audit-logger.ts +6 -29
  50. package/src/runtime/audit.ts +598 -0
  51. package/src/runtime/base.ts +154 -99
  52. package/src/runtime/needs-authorization.ts +47 -0
  53. package/src/services/__tests__/oauth-config.service.test.ts +66 -0
  54. package/src/services/__tests__/proof-verifier.integration.test.ts +1 -1
  55. package/src/services/__tests__/proof-verifier.test.ts +6 -3
  56. package/src/services/oauth-config.service.ts +44 -1
  57. package/src/__tests__/runtime/audit-logger.test.ts +0 -154
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.toNeedsAuthorization = toNeedsAuthorization;
4
+ /**
5
+ * C4 (#2918) 3c envelope flip — `DelegationRequiredError` → `needs_authorization`.
6
+ *
7
+ * Projects the internal `DelegationRequiredError` control-flow signal onto the
8
+ * ratified DIF `needs_authorization` envelope so the tool-call gate can dual-emit
9
+ * the canonical wire shape alongside the legacy proprietary `_meta` keys (the
10
+ * wire-format dual-accept thesis: read accepts both; emit moves to the new form;
11
+ * legacy keys stay until the telemetry-gated sunset).
12
+ *
13
+ * Envelope-flip ONLY — N-of-M step-up (`needs_approval` / `NeedsApprovalError`)
14
+ * is deferred to the T3-edge step-up lane (#3222) and is intentionally NOT
15
+ * produced here.
16
+ *
17
+ * The shape + builder are sourced from `@kya-os/contracts/runtime` (the ratified
18
+ * source that DIF `@kya-os/mcp` mirrors) rather than `@kya-os/mcp` directly: this
19
+ * package is CommonJS (`module: Node16`) and `@kya-os/mcp` is ESM-only, so a
20
+ * static value import would not resolve from CJS. `auth/handshake.ts` already
21
+ * builds `NeedsAuthorizationError` from `@kya-os/contracts/runtime` for the same
22
+ * reason — this mirrors that convention.
23
+ */
24
+ const runtime_1 = require("@kya-os/contracts/runtime");
25
+ /**
26
+ * Build the DIF `needs_authorization` envelope from a `DelegationRequiredError`.
27
+ *
28
+ * @param err - the thrown delegation signal (already carries `consentUrl`,
29
+ * `resumeToken`, and `requiredScopes` populated at every throw site).
30
+ * @param expiresAtMs - resume-token expiry as **milliseconds since epoch**, the
31
+ * unit the contracts schema expects and that `clock.calculateExpiry()` returns
32
+ * (`now() + ttlSeconds * 1000`). Pass `interceptedCall.expiresAt` directly.
33
+ */
34
+ function toNeedsAuthorization(err, expiresAtMs) {
35
+ return (0, runtime_1.createNeedsAuthorizationError)({
36
+ message: `Authorization required for tool "${err.toolName}".`,
37
+ authorizationUrl: err.consentUrl ?? "",
38
+ resumeToken: err.resumeToken ?? "",
39
+ expiresAt: expiresAtMs,
40
+ scopes: err.requiredScopes,
41
+ });
42
+ }
43
+ //# sourceMappingURL=needs-authorization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"needs-authorization.js","sourceRoot":"","sources":["../../src/runtime/needs-authorization.ts"],"names":[],"mappings":";;AAmCA,oDAWC;AA9CD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,uDAGmC;AAGnC;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAClC,GAA4B,EAC5B,WAAmB;IAEnB,OAAO,IAAA,uCAA6B,EAAC;QACnC,OAAO,EAAE,oCAAoC,GAAG,CAAC,QAAQ,IAAI;QAC7D,gBAAgB,EAAE,GAAG,CAAC,UAAU,IAAI,EAAE;QACtC,WAAW,EAAE,GAAG,CAAC,WAAW,IAAI,EAAE;QAClC,SAAS,EAAE,WAAW;QACtB,MAAM,EAAE,GAAG,CAAC,cAAc;KAC3B,CAAC,CAAC;AACL,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-config.service.d.ts","sourceRoot":"","sources":["../../src/services/oauth-config.service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAiB,MAAM,0BAA0B,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAGvE,MAAM,WAAW,wBAAwB;IACvC,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAEhB,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAC;IAEf,8CAA8C;IAC9C,aAAa,EAAE,aAAa,CAAC;IAE7B,mDAAmD;IACnD,KAAK,CAAC,EAAE,gBAAgB,CAAC;IAEzB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,+CAA+C;IAC/C,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;CACpD;AAED;;GAEG;AACH,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,MAAM,CAGZ;gBAEU,MAAM,EAAE,wBAAwB;IAW5C;;;;;;;;OAQG;IACG,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IA8G7D;;;;OAIG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKlD;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;CAIrC"}
1
+ {"version":3,"file":"oauth-config.service.d.ts","sourceRoot":"","sources":["../../src/services/oauth-config.service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EACV,WAAW,EAGZ,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAC;AAiCvE,MAAM,WAAW,wBAAwB;IACvC,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAEhB,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAC;IAEf,8CAA8C;IAC9C,aAAa,EAAE,aAAa,CAAC;IAE7B,mDAAmD;IACnD,KAAK,CAAC,EAAE,gBAAgB,CAAC;IAEzB,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,+CAA+C;IAC/C,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;CACpD;AAED;;GAEG;AACH,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,MAAM,CAGZ;gBAEU,MAAM,EAAE,wBAAwB;IAW5C;;;;;;;;OAQG;IACG,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IAuH7D;;;;OAIG;IACG,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKlD;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;CAIrC"}
@@ -10,6 +10,26 @@
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.OAuthConfigService = void 0;
12
12
  const oauth_config_cache_js_1 = require("../cache/oauth-config-cache.js");
13
+ /**
14
+ * Normalize a provider's secret-reference metadata from the AgentShield
15
+ * `/providers` response into the OAuthProvider `metadata` shape.
16
+ *
17
+ * The response may use camelCase or snake_case; only the secret-*name*
18
+ * references are carried (never the secret values). Returns `undefined` when
19
+ * no metadata is present so the field stays absent on the parsed provider.
20
+ */
21
+ function mapProviderSecretMetadata(raw) {
22
+ if (!raw || typeof raw !== "object")
23
+ return undefined;
24
+ const m = raw;
25
+ const metadata = {
26
+ clientSecretName: (m.clientSecretName ?? m.client_secret_name),
27
+ clientIdSecretName: (m.clientIdSecretName ?? m.client_id_secret_name),
28
+ apiKeySecretName: (m.apiKeySecretName ?? m.api_key_secret_name),
29
+ clientSecretVersion: (m.clientSecretVersion ?? m.client_secret_version),
30
+ };
31
+ return metadata;
32
+ }
13
33
  /**
14
34
  * Service for fetching OAuth provider configurations from AgentShield API
15
35
  */
@@ -91,6 +111,15 @@ class OAuthConfigService {
91
111
  tokenEndpointAuthMethod: (p.tokenEndpointAuthMethod ?? p.token_endpoint_auth_method),
92
112
  responseType: (p.responseType ?? p.response_type),
93
113
  grantType: (p.grantType ?? p.grant_type),
114
+ // Provider-registry secret metadata (clientSecretName etc.). REQUIRED:
115
+ // OAuthService.resolveClientSecret resolves a confidential provider's
116
+ // client secret from secure storage via `metadata.clientSecretName`
117
+ // (the AgentShield /providers response intentionally omits the plaintext
118
+ // `clientSecret`). Without mapping this field here, `metadata` is
119
+ // undefined, resolveClientSecret falls back to the (absent) inline
120
+ // clientSecret, and the worker sends an empty secret — token exchange
121
+ // then fails with "client_id and/or client_secret incorrect".
122
+ metadata: mapProviderSecretMetadata(p.metadata),
94
123
  };
95
124
  }
96
125
  // Build OAuthConfig object
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-config.service.js","sourceRoot":"","sources":["../../src/services/oauth-config.service.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAKH,0EAA0E;AAsB1E;;GAEG;AACH,MAAa,kBAAkB;IACrB,MAAM,CAGZ;IAEF,YAAY,MAAgC;QAC1C,IAAI,CAAC,MAAM,GAAG;YACZ,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,aAAa,EAAE,MAAM,CAAC,aAAa;YACnC,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,oBAAoB;YAChE,MAAM,E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AAC;QACd,CAAC;IACH,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,UAAU,CAAC,SAAiB;QAChC,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,oCAAoC,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IAC1E,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa;QACjB,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,wCAAwC,CAAC,CAAC;IAC/D,CAAC;CACF;AAlKD,gDAkKC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kya-os/mcp-i-runtime",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Shared product-runtime layer for the MCP-I framework (Node + Cloudflare adapters). Protocol types/values live in @kya-os/mcp (DIF).",
5
5
  "license": "MIT",
6
6
  "author": "Dylan Hobbs",
@@ -24,6 +24,10 @@
24
24
  "types": "./dist/runtime/audit-logger.d.ts",
25
25
  "default": "./dist/runtime/audit-logger.js"
26
26
  },
27
+ "./runtime/audit": {
28
+ "types": "./dist/runtime/audit.d.ts",
29
+ "default": "./dist/runtime/audit.js"
30
+ },
27
31
  "./runtime/ext-apps-constants": {
28
32
  "types": "./dist/runtime/ext-apps-constants.d.ts",
29
33
  "default": "./dist/runtime/ext-apps-constants.js"
@@ -55,8 +59,8 @@
55
59
  "prepublishOnly": "npm run build && node ../create-mcpi-app/scripts/validate-no-workspace.js"
56
60
  },
57
61
  "dependencies": {
58
- "@kya-os/contracts": "^1.8.0",
59
- "@kya-os/mcp": "^1.6.1",
62
+ "@kya-os/contracts": "^1.10.0",
63
+ "@kya-os/mcp": "1.11.0",
60
64
  "jose": "^5.6.3",
61
65
  "json-canonicalize": "^2.0.0",
62
66
  "zod": "^3.25.67"
@@ -241,10 +241,6 @@ describe('ProviderRuntimeConfig', () => {
241
241
  apiKey: 'as-key',
242
242
  },
243
243
  },
244
- audit: {
245
- enabled: true,
246
- includeProofHashes: false,
247
- },
248
244
  wellKnown: {
249
245
  enabled: true,
250
246
  serviceName: 'Test Service',
@@ -257,7 +253,7 @@ describe('ProviderRuntimeConfig', () => {
257
253
  expect(config.proofing?.enabled).toBe(true);
258
254
  expect(config.delegation?.enabled).toBe(true);
259
255
  expect(config.toolProtection?.source).toBe('agentshield');
260
- expect(config.audit?.enabled).toBe(true);
256
+ expect(config).not.toHaveProperty('audit');
261
257
  expect(config.wellKnown?.enabled).toBe(true);
262
258
  });
263
259
  });
@@ -272,9 +268,6 @@ describe('ProviderRuntimeConfig', () => {
272
268
  storageProvider: mockStorageProvider,
273
269
  nonceCacheProvider: mockNonceCacheProvider,
274
270
  identityProvider: mockIdentityProvider,
275
- audit: {
276
- enabled: true,
277
- },
278
271
  wellKnown: {
279
272
  enabled: true,
280
273
  },
@@ -282,7 +275,7 @@ describe('ProviderRuntimeConfig', () => {
282
275
 
283
276
  // MCPIBaseConfig fields should be available
284
277
  expect(config.environment).toBeDefined();
285
- expect(config.audit).toBeDefined();
278
+ expect(config).not.toHaveProperty('audit');
286
279
  expect(config.wellKnown).toBeDefined();
287
280
  });
288
281
 
@@ -22,6 +22,7 @@ import type {
22
22
  IdentityProvider,
23
23
  } from "../providers/base";
24
24
  import type { ToolProtectionService } from "../services/tool-protection.service";
25
+ import type { RuntimeAuditConfig } from "../runtime/audit";
25
26
 
26
27
  describe("ProviderRuntimeConfigBuilder", () => {
27
28
  // Create mock providers
@@ -194,19 +195,21 @@ describe("ProviderRuntimeConfigBuilder", () => {
194
195
  });
195
196
  });
196
197
 
197
- describe("withAudit", () => {
198
- it("should set audit config", () => {
198
+ describe("withAuditTrail", () => {
199
+ it("should set the canonical audit trail without a diagnostic logger", () => {
199
200
  const providers = createMockProviders();
201
+ const auditTrail = {
202
+ trail: { record: vi.fn() },
203
+ context: { create: vi.fn() },
204
+ sourceId: "deployment:test",
205
+ } as unknown as RuntimeAuditConfig;
200
206
  const config = new ProviderRuntimeConfigBuilder()
201
207
  .withProviders(providers)
202
- .withAudit({
203
- enabled: true,
204
- includeProofHashes: true,
205
- })
208
+ .withAuditTrail(auditTrail)
206
209
  .build();
207
210
 
208
- expect(config.audit?.enabled).toBe(true);
209
- expect(config.audit?.includeProofHashes).toBe(true);
211
+ expect(config.auditTrail).toBe(auditTrail);
212
+ expect(config).not.toHaveProperty("audit");
210
213
  });
211
214
  });
212
215
 
@@ -250,12 +253,11 @@ describe("ProviderRuntimeConfigBuilder", () => {
250
253
  .withProviders(providers)
251
254
  .withEnvironment("production")
252
255
  .withSession({ ttlMinutes: 60 })
253
- .withAudit({ enabled: true })
254
256
  .build();
255
257
 
256
258
  expect(config.environment).toBe("production");
257
259
  expect(config.session?.ttlMinutes).toBe(60);
258
- expect(config.audit?.enabled).toBe(true);
260
+ expect(config).not.toHaveProperty("audit");
259
261
  });
260
262
  });
261
263
  });
@@ -304,4 +306,3 @@ describe("createProviderRuntimeConfig", () => {
304
306
 
305
307
 
306
308
 
307
-
@@ -104,11 +104,6 @@ describe("Full Flow Integration", () => {
104
104
  timestampSkewSeconds: 120,
105
105
  ttlMinutes: 30,
106
106
  },
107
- audit: {
108
- enabled: true,
109
- logFunction: vi.fn(),
110
- includePayloads: true,
111
- },
112
107
  toolProtection: {
113
108
  source: "agentshield",
114
109
  agentShield: {
@@ -33,11 +33,7 @@ describe('Integration Tests', () => {
33
33
  identityProvider: new MemoryIdentityProvider(cryptoProvider),
34
34
  environment: 'development',
35
35
  timestampSkewSeconds: 120,
36
- sessionTtlMinutes: 30,
37
- audit: {
38
- enabled: true,
39
- includePayloads: true
40
- }
36
+ sessionTtlMinutes: 30
41
37
  });
42
38
 
43
39
  await runtime.initialize();
@@ -278,4 +274,4 @@ describe('Integration Tests', () => {
278
274
  expect(debugEndpoint).toBeNull();
279
275
  });
280
276
  });
281
- });
277
+ });
@@ -0,0 +1,327 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import type { AuditTrailEventInput } from "@kya-os/mcp/audit";
3
+ import type { ProviderRuntimeConfig } from "../../config";
4
+ import { MCPIRuntimeBase } from "../../runtime/base";
5
+ import {
6
+ createHmacRuntimeAuditContextFactory,
7
+ recordRuntimeConsentAudit,
8
+ recordRuntimeDelegationAudit,
9
+ type RuntimeAuditConfig,
10
+ } from "../../runtime/audit";
11
+ import { createMockProviders } from "../utils/mock-providers";
12
+
13
+ function auditConfig(record: (event: AuditTrailEventInput) => Promise<unknown>): RuntimeAuditConfig {
14
+ return {
15
+ sourceId: "deployment:test:mcp:0",
16
+ context: {
17
+ create: async () => ({
18
+ invocationId: "invocation-1",
19
+ correlationId: "correlation-1",
20
+ session: {
21
+ ref: {
22
+ kind: "keyed_commitment",
23
+ value: `sha256:${"a".repeat(64)}`,
24
+ keyId: "session-key-1",
25
+ },
26
+ },
27
+ }),
28
+ },
29
+ trail: { record: record as RuntimeAuditConfig["trail"]["record"] },
30
+ includeToolNames: true,
31
+ };
32
+ }
33
+
34
+ function runtimeWithAudit(record: (event: AuditTrailEventInput) => Promise<unknown>): MCPIRuntimeBase {
35
+ const config: ProviderRuntimeConfig = {
36
+ ...createMockProviders(),
37
+ environment: "development",
38
+ auditTrail: auditConfig(record),
39
+ };
40
+ return new MCPIRuntimeBase(config);
41
+ }
42
+
43
+ function pendingResult(event: AuditTrailEventInput, sourceSequence = "1") {
44
+ return {
45
+ status: "pending",
46
+ event: {
47
+ ...event,
48
+ source: {
49
+ producer: { kind: "pairwise_did", did: "did:key:zProducer" },
50
+ sourceId: "deployment:test:mcp:0",
51
+ sourceSequence,
52
+ },
53
+ },
54
+ };
55
+ }
56
+
57
+ describe("canonical runtime audit lifecycle", () => {
58
+ it("records exactly one started and one completed event", async () => {
59
+ const events: AuditTrailEventInput[] = [];
60
+ const runtime = runtimeWithAudit(async (event) => {
61
+ events.push(event);
62
+ return pendingResult(event, String(events.length));
63
+ });
64
+ const handler = vi.fn(async () => ({ ok: true }));
65
+
66
+ const result = await runtime.processToolCall(
67
+ "payments.send",
68
+ { secret: "never-audited" },
69
+ handler,
70
+ { id: "raw-session", nonce: "nonce", audience: "client" },
71
+ );
72
+
73
+ expect(result).toMatchObject({
74
+ ok: true,
75
+ _meta: {
76
+ "org.kya-os/audit": {
77
+ status: "pending",
78
+ sourceId: "deployment:test:mcp:0",
79
+ invocationId: "invocation-1",
80
+ },
81
+ },
82
+ });
83
+
84
+ expect(handler).toHaveBeenCalledTimes(1);
85
+ expect(events.map((event) => event.eventType)).toEqual([
86
+ "tool.call.started",
87
+ "tool.call.completed",
88
+ ]);
89
+ expect(events.map((event) => event.eventId)).toEqual([
90
+ "invocation-1:started",
91
+ "invocation-1:completed",
92
+ ]);
93
+ expect(events.every((event) => event.correlationId === "correlation-1")).toBe(true);
94
+ expect(JSON.stringify(events)).not.toContain("never-audited");
95
+ expect(JSON.stringify(events)).not.toContain("raw-session");
96
+ });
97
+
98
+ it("records one failed terminal event and never re-runs a throwing handler", async () => {
99
+ const events: AuditTrailEventInput[] = [];
100
+ const runtime = runtimeWithAudit(async (event) => {
101
+ events.push(event);
102
+ return pendingResult(event, String(events.length));
103
+ });
104
+ const handler = vi.fn(async () => {
105
+ throw new Error("side effect failed");
106
+ });
107
+
108
+ await expect(runtime.processToolCall(
109
+ "payments.send",
110
+ {},
111
+ handler,
112
+ { id: "session", nonce: "nonce", audience: "client" },
113
+ )).rejects.toThrow("side effect failed");
114
+
115
+ expect(handler).toHaveBeenCalledTimes(1);
116
+ expect(events.map((event) => event.eventType)).toEqual([
117
+ "tool.call.started",
118
+ "tool.call.failed",
119
+ ]);
120
+ });
121
+
122
+ it("keeps long started and terminal event IDs distinct", async () => {
123
+ const events: AuditTrailEventInput[] = [];
124
+ const config = auditConfig(async (event) => {
125
+ events.push(event);
126
+ return pendingResult(event, String(events.length));
127
+ });
128
+ config.context = {
129
+ create: async () => ({
130
+ invocationId: "i".repeat(256),
131
+ correlationId: "correlation-1",
132
+ }),
133
+ };
134
+ const runtime = new MCPIRuntimeBase({
135
+ ...createMockProviders(),
136
+ environment: "development",
137
+ auditTrail: config,
138
+ });
139
+
140
+ await runtime.processToolCall("payments.send", {}, async () => ({ ok: true }));
141
+
142
+ expect(events.map((event) => event.eventId)).toHaveLength(2);
143
+ expect(events[0].eventId).not.toBe(events[1].eventId);
144
+ expect(events[0].eventId).toHaveLength(256);
145
+ expect(events[1].eventId).toHaveLength(256);
146
+ expect(events[0].eventId).toMatch(/:started$/);
147
+ expect(events[1].eventId).toMatch(/:completed$/);
148
+ });
149
+
150
+ it("does not execute the handler when required intent delivery rejects", async () => {
151
+ const runtime = runtimeWithAudit(async () => {
152
+ throw new Error("recorder unavailable");
153
+ });
154
+ const handler = vi.fn(async () => ({ ok: true }));
155
+
156
+ await expect(runtime.processToolCall("dangerous", {}, handler, {
157
+ id: "session",
158
+ nonce: "nonce",
159
+ audience: "client",
160
+ })).rejects.toThrow("recorder unavailable");
161
+ expect(handler).not.toHaveBeenCalled();
162
+ });
163
+
164
+ it("classifies inline consent as a challenged terminal event", async () => {
165
+ const events: AuditTrailEventInput[] = [];
166
+ const runtime = runtimeWithAudit(async (event) => {
167
+ events.push(event);
168
+ return pendingResult(event, String(events.length));
169
+ });
170
+
171
+ await runtime.processToolCall("protected", {}, async () => ({
172
+ structuredContent: { type: "consent_required" },
173
+ _meta: { ui: { resourceUri: "ui://kya-os-consent/authorize" } },
174
+ }), { id: "session", nonce: "nonce", audience: "client" });
175
+
176
+ expect(events.map((event) => event.eventType)).toEqual([
177
+ "tool.call.started",
178
+ "tool.call.challenged",
179
+ ]);
180
+ });
181
+
182
+ it("does not emit twice or rerun the handler when successful terminal delivery throws", async () => {
183
+ const events: AuditTrailEventInput[] = [];
184
+ const runtime = runtimeWithAudit(async (event) => {
185
+ events.push(event);
186
+ if (event.eventType === "tool.call.completed") {
187
+ throw new Error("required recorder unavailable");
188
+ }
189
+ return pendingResult(event);
190
+ });
191
+ const handler = vi.fn(async () => ({
192
+ content: [{ type: "text", text: "paid" }],
193
+ _meta: {
194
+ proof: { jws: "proof-is-preserved" },
195
+ foreignExtension: { enabled: true },
196
+ },
197
+ }));
198
+
199
+ const result = await runtime.processToolCall("payments.send", {}, handler, {
200
+ id: "session",
201
+ nonce: "nonce",
202
+ audience: "client",
203
+ });
204
+
205
+ expect(handler).toHaveBeenCalledTimes(1);
206
+ expect(events.map((event) => event.eventType)).toEqual([
207
+ "tool.call.started",
208
+ "tool.call.completed",
209
+ ]);
210
+ expect(result).toMatchObject({
211
+ isError: true,
212
+ _meta: {
213
+ proof: { jws: "proof-is-preserved" },
214
+ foreignExtension: { enabled: true },
215
+ "org.kya-os/audit": {
216
+ status: "degraded",
217
+ reason: "AUDIT_TERMINAL_DELIVERY_FAILED",
218
+ events: [{ eventType: "tool.call.started" }],
219
+ },
220
+ },
221
+ });
222
+ });
223
+
224
+ it("fails closed for primitive results after required terminal delivery failure", async () => {
225
+ const events: AuditTrailEventInput[] = [];
226
+ const runtime = runtimeWithAudit(async (event) => {
227
+ events.push(event);
228
+ if (event.eventType === "tool.call.completed") throw new Error("offline");
229
+ return pendingResult(event);
230
+ });
231
+ const handler = vi.fn(async () => "side-effect-complete");
232
+
233
+ await expect(runtime.processToolCall("payments.send", {}, handler)).rejects.toThrow(
234
+ "Required terminal audit delivery failed after tool execution",
235
+ );
236
+ expect(handler).toHaveBeenCalledTimes(1);
237
+ expect(events.map((event) => event.eventType)).toEqual([
238
+ "tool.call.started",
239
+ "tool.call.completed",
240
+ ]);
241
+ });
242
+ });
243
+
244
+ describe("HMAC audit references", () => {
245
+ it("is deterministic and does not expose capability-bearing identifiers", async () => {
246
+ const factory = createHmacRuntimeAuditContextFactory({
247
+ secret: "0123456789abcdef0123456789abcdef",
248
+ keyId: "audit-ref-2026-01",
249
+ randomUUID: () => "fallback-invocation",
250
+ });
251
+ const input = {
252
+ toolName: "payments.send",
253
+ args: {},
254
+ session: {
255
+ id: "session-secret",
256
+ clientDid: "did:key:zClient",
257
+ auditInvocationId: "request-secret",
258
+ auditCorrelationId: "flow-secret",
259
+ },
260
+ };
261
+
262
+ const first = await factory.create(input);
263
+ const second = await factory.create(input);
264
+
265
+ expect(second).toEqual(first);
266
+ expect(first.session?.ref.kind).toBe("keyed_commitment");
267
+ expect(first.actor).toEqual({ kind: "public_did", did: "did:key:zClient" });
268
+ const serialized = JSON.stringify(first);
269
+ expect(serialized).not.toContain("session-secret");
270
+ expect(serialized).not.toContain("request-secret");
271
+ expect(serialized).not.toContain("flow-secret");
272
+ });
273
+ });
274
+
275
+ describe("canonical consent and delegation events", () => {
276
+ it("records consent without copying request payload fields", async () => {
277
+ const events: AuditTrailEventInput[] = [];
278
+ await recordRuntimeConsentAudit(auditConfig(async (event) => {
279
+ events.push(event);
280
+ return pendingResult(event);
281
+ }), {
282
+ phase: "credential_failed",
283
+ outcome: "failed",
284
+ sessionId: "raw-session-secret",
285
+ userDid: "did:key:zUser",
286
+ reasonCode: "CREDENTIAL_AUTH_FAILED",
287
+ consentRef: "consent-reference",
288
+ });
289
+
290
+ expect(events).toHaveLength(1);
291
+ expect(events[0]).toMatchObject({
292
+ eventType: "credential.failed",
293
+ action: { category: "consent" },
294
+ outcome: "failed",
295
+ reason: { code: "CREDENTIAL_AUTH_FAILED" },
296
+ details: {
297
+ family: "consent",
298
+ phase: "credential_failed",
299
+ consentRef: "consent-reference",
300
+ },
301
+ });
302
+ expect(JSON.stringify(events[0])).not.toContain("raw-session-secret");
303
+ });
304
+
305
+ it("records delegation issuance as a separate event family", async () => {
306
+ const events: AuditTrailEventInput[] = [];
307
+ await recordRuntimeDelegationAudit(auditConfig(async (event) => {
308
+ events.push(event);
309
+ return pendingResult(event);
310
+ }), {
311
+ phase: "issued",
312
+ outcome: "succeeded",
313
+ sessionId: "session-secret",
314
+ delegationRef: "delegation-123",
315
+ });
316
+
317
+ expect(events[0]).toMatchObject({
318
+ eventType: "delegation.issued",
319
+ action: { category: "delegation" },
320
+ details: {
321
+ family: "delegation",
322
+ phase: "issued",
323
+ delegationRef: "delegation-123",
324
+ },
325
+ });
326
+ });
327
+ });
@@ -25,9 +25,6 @@ describe('MCPIRuntimeBase - Base Extensions', () => {
25
25
  session: {
26
26
  timestampSkewSeconds: 120,
27
27
  ttlMinutes: 30
28
- },
29
- audit: {
30
- enabled: false
31
28
  }
32
29
  };
33
30
  runtime = new MCPIRuntimeBase(config);
@@ -304,48 +301,6 @@ describe('MCPIRuntimeBase - Base Extensions', () => {
304
301
  });
305
302
  });
306
303
 
307
- describe('getAuditLogger', () => {
308
- it('should return logger with log method', () => {
309
- const logger = runtime.getAuditLogger();
310
- expect(logger).toBeDefined();
311
- expect(typeof logger.log).toBe('function');
312
- });
313
-
314
- it('should log through runtime audit system', async () => {
315
- const auditConfig = {
316
- ...config,
317
- audit: {
318
- enabled: true,
319
- logFunction: vi.fn(),
320
- includePayloads: true
321
- }
322
- };
323
- const auditRuntime = new MCPIRuntimeBase(auditConfig);
324
- await auditRuntime.initialize();
325
-
326
- const logger = auditRuntime.getAuditLogger();
327
- logger.log('test_event', { test: 'data' });
328
-
329
- expect(auditConfig.audit!.logFunction).toHaveBeenCalledWith(
330
- expect.stringContaining('test_event')
331
- );
332
- });
333
-
334
- it('should handle audit disabled', () => {
335
- const noAuditConfig = {
336
- ...config,
337
- audit: {
338
- enabled: false
339
- }
340
- };
341
- const noAuditRuntime = new MCPIRuntimeBase(noAuditConfig);
342
- const logger = noAuditRuntime.getAuditLogger();
343
-
344
- // Should not throw
345
- logger.log('test_event', { test: 'data' });
346
- });
347
- });
348
-
349
304
  describe('rotateKeys', () => {
350
305
  beforeEach(async () => {
351
306
  await runtime.initialize();
@@ -592,4 +547,3 @@ describe('MCPIRuntimeBase - Base Extensions', () => {
592
547
  });
593
548
  });
594
549
  });
595
-