@kya-os/mcp-i-runtime 1.1.0 → 1.2.1

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 (63) 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 +3 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +20 -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/services/auth-type-satisfies.d.ts +93 -0
  23. package/dist/services/auth-type-satisfies.d.ts.map +1 -0
  24. package/dist/services/auth-type-satisfies.js +127 -0
  25. package/dist/services/auth-type-satisfies.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/dist/services/tool-context-builder.d.ts +6 -1
  30. package/dist/services/tool-context-builder.d.ts.map +1 -1
  31. package/dist/services/tool-context-builder.js +35 -3
  32. package/dist/services/tool-context-builder.js.map +1 -1
  33. package/package.json +7 -3
  34. package/src/__tests__/config/provider-runtime-config.test.ts +2 -9
  35. package/src/__tests__/config.test.ts +12 -11
  36. package/src/__tests__/integration/full-flow.test.ts +0 -5
  37. package/src/__tests__/integration.test.ts +2 -6
  38. package/src/__tests__/runtime/audit.test.ts +327 -0
  39. package/src/__tests__/runtime/base-extensions.test.ts +0 -46
  40. package/src/__tests__/runtime/base.test.ts +71 -102
  41. package/src/__tests__/runtime/delegation-flow.test.ts +0 -4
  42. package/src/__tests__/runtime/process-tool-call-security.test.ts +5 -11
  43. package/src/__tests__/runtime/proof-client-did.test.ts +0 -4
  44. package/src/__tests__/runtime/provider-selection.test.ts +0 -2
  45. package/src/__tests__/runtime/route-interception.test.ts +7 -4
  46. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +23 -31
  47. package/src/__tests__/services/tool-protection-merged-config.test.ts +0 -40
  48. package/src/config/__tests__/merged-config.spec.ts +0 -26
  49. package/src/config.ts +9 -10
  50. package/src/index.ts +32 -2
  51. package/src/runtime/__tests__/audit-logger-compat.test.ts +15 -0
  52. package/src/runtime/audit-logger.ts +6 -29
  53. package/src/runtime/audit.ts +598 -0
  54. package/src/runtime/base.ts +154 -99
  55. package/src/services/__tests__/auth-type-satisfies.test.ts +232 -0
  56. package/src/services/__tests__/oauth-config.service.test.ts +66 -0
  57. package/src/services/__tests__/proof-verifier.integration.test.ts +1 -1
  58. package/src/services/__tests__/proof-verifier.test.ts +6 -3
  59. package/src/services/__tests__/tool-context-builder-authtype.test.ts +167 -0
  60. package/src/services/auth-type-satisfies.ts +134 -0
  61. package/src/services/oauth-config.service.ts +44 -1
  62. package/src/services/tool-context-builder.ts +64 -18
  63. package/src/__tests__/runtime/audit-logger.test.ts +0 -154
@@ -39,7 +39,17 @@ import {
39
39
  type OAuthIdentity,
40
40
  } from "../identity/user-did-manager";
41
41
  import type { InterceptedToolCall } from "../types/tool-protection.js";
42
- import type { IAuditLogger } from "./audit-logger.js";
42
+ import {
43
+ attachRuntimeAuditMetadata,
44
+ beginRuntimeToolAudit,
45
+ recordRuntimeConsentAudit,
46
+ recordRuntimeDelegationAudit,
47
+ resolveRuntimeAuditAssurance,
48
+ terminalForToolError,
49
+ terminalForToolResult,
50
+ type RuntimeConsentAuditInput,
51
+ type RuntimeDelegationAuditInput,
52
+ } from "./audit.js";
43
53
  import {
44
54
  SESSION_ID_PREFIX,
45
55
  WELL_KNOWN_IDENTITY_PATH,
@@ -75,6 +85,7 @@ interface RuntimeHandshakeResponse {
75
85
  agentDid: string;
76
86
  timestamp: number;
77
87
  capabilities: string[];
88
+ auditAssurance: ReturnType<typeof resolveRuntimeAuditAssurance>;
78
89
  userDid?: string;
79
90
  signature: string;
80
91
  }
@@ -121,12 +132,6 @@ interface LegacyProof {
121
132
 
122
133
  type RuntimeProof = LegacyProof | DetachedProof;
123
134
 
124
- type RuntimeAuditLogger =
125
- | IAuditLogger
126
- | {
127
- log: (event: string, data: unknown) => void;
128
- };
129
-
130
135
  interface NonceCacheWithInitialize extends NonceCacheProvider {
131
136
  initialize?: () => Promise<void> | void;
132
137
  }
@@ -202,9 +207,8 @@ export class MCPIRuntimeBase {
202
207
  await nonceCacheWithInitialize.initialize();
203
208
  }
204
209
 
205
- // Log initialization if audit is enabled
206
- if (this.config.audit?.enabled) {
207
- this.logAudit("runtime_initialized", {
210
+ if (this.config.environment === "development") {
211
+ this.emitDiagnostic("runtime_initialized", {
208
212
  did: this.cachedIdentity.did,
209
213
  environment: this.config.environment || "development",
210
214
  userDidGeneration: this.config.identity?.generateUserDids
@@ -224,6 +228,18 @@ export class MCPIRuntimeBase {
224
228
  return this.cachedIdentity;
225
229
  }
226
230
 
231
+ /** Record a canonical consent/credential event when a trail is configured. */
232
+ async recordConsentAudit(input: RuntimeConsentAuditInput) {
233
+ if (this.config.auditTrail === undefined) return undefined;
234
+ return recordRuntimeConsentAudit(this.config.auditTrail, input);
235
+ }
236
+
237
+ /** Record a canonical delegation event when a trail is configured. */
238
+ async recordDelegationAudit(input: RuntimeDelegationAuditInput) {
239
+ if (this.config.auditTrail === undefined) return undefined;
240
+ return recordRuntimeDelegationAudit(this.config.auditTrail, input);
241
+ }
242
+
227
243
  /**
228
244
  * Handle MCP handshake request
229
245
  *
@@ -267,7 +283,7 @@ export class MCPIRuntimeBase {
267
283
  // Convert null to undefined for session storage
268
284
  userDid = resolvedDid ?? undefined;
269
285
 
270
- if (this.config.audit?.enabled) {
286
+ if (this.config.environment === "development") {
271
287
  if (userDid) {
272
288
  console.error("[MCP-I] Resolved existing user DID for session:", {
273
289
  userDid: userDid.substring(0, 20) + "...",
@@ -341,11 +357,17 @@ export class MCPIRuntimeBase {
341
357
  this.sessions.set(sessionId, session);
342
358
 
343
359
  // Create handshake response
360
+ const auditAssurance = resolveRuntimeAuditAssurance(this.config.auditTrail);
344
361
  const response = {
345
362
  sessionId,
346
363
  agentDid: identity.did,
347
364
  timestamp,
348
- capabilities: ["identity", "proof", "audit"],
365
+ capabilities: [
366
+ "identity",
367
+ "proof",
368
+ ...(auditAssurance.enabled ? ["audit-trail"] : []),
369
+ ],
370
+ auditAssurance,
349
371
  ...(userDid && { userDid }), // Include user DID in response if generated
350
372
  };
351
373
 
@@ -398,7 +420,7 @@ export class MCPIRuntimeBase {
398
420
  );
399
421
  }
400
422
 
401
- if (this.config.audit?.enabled) {
423
+ if (this.config.environment === "development") {
402
424
  console.error("[MCP-I] Session identity updated (Phase 5):", {
403
425
  sessionId: sessionId.substring(0, 8) + "...",
404
426
  userDid: userDid.substring(0, 20) + "...",
@@ -467,13 +489,78 @@ export class MCPIRuntimeBase {
467
489
  args: TArgs,
468
490
  handler: (args: TArgs) => Promise<TResult>,
469
491
  session?: RuntimeSessionContext
492
+ ): Promise<TResult | RuntimeRecord> {
493
+ const auditInvocation = this.config.auditTrail
494
+ ? await beginRuntimeToolAudit(this.config.auditTrail, {
495
+ toolName,
496
+ args,
497
+ session,
498
+ })
499
+ : undefined;
500
+
501
+ let result: TResult | RuntimeRecord;
502
+ try {
503
+ result = await this.processToolCallInternal(
504
+ toolName,
505
+ args,
506
+ handler,
507
+ session
508
+ );
509
+ } catch (error) {
510
+ if (auditInvocation) {
511
+ try {
512
+ await auditInvocation.terminal(terminalForToolError(error));
513
+ } catch (auditError) {
514
+ // A tool failure is the primary error. Do not replace it with a
515
+ // terminal-delivery error and accidentally make retries ambiguous.
516
+ console.error("[MCP-I] Failed to record terminal tool audit event", {
517
+ error: auditError instanceof Error ? auditError.message : String(auditError),
518
+ });
519
+ }
520
+ }
521
+ throw error;
522
+ }
523
+
524
+ if (!auditInvocation || !this.config.auditTrail) return result;
525
+
526
+ try {
527
+ const terminal = await auditInvocation.terminal(terminalForToolResult(result));
528
+ return attachRuntimeAuditMetadata(
529
+ result,
530
+ this.config.auditTrail.sourceId,
531
+ auditInvocation.context.invocationId,
532
+ auditInvocation.results(terminal)
533
+ );
534
+ } catch (auditError) {
535
+ // The tool side effect has already completed. Never execute it again and
536
+ // never attempt a second terminal event. Object-shaped MCP results carry
537
+ // an explicit degraded/error marker; primitives fail closed because they
538
+ // cannot carry trustworthy delivery metadata.
539
+ console.error("[MCP-I] Failed to record successful tool audit terminal", {
540
+ error: auditError instanceof Error ? auditError.message : String(auditError),
541
+ });
542
+ return attachRuntimeAuditMetadata(
543
+ result,
544
+ this.config.auditTrail.sourceId,
545
+ auditInvocation.context.invocationId,
546
+ auditInvocation.results(),
547
+ true
548
+ );
549
+ }
550
+ }
551
+
552
+ private async processToolCallInternal<TArgs = unknown, TResult = unknown>(
553
+ toolName: string,
554
+ args: TArgs,
555
+ handler: (args: TArgs) => Promise<TResult>,
556
+ session?: RuntimeSessionContext
470
557
  ): Promise<TResult | RuntimeRecord> {
471
558
  // Check tool protection (delegation requirement)
472
559
  if (this.config.toolProtectionService) {
473
560
  // Get agent identity to check protection
474
561
  const identity = await this.getIdentity();
475
562
 
476
- if (this.config.audit?.enabled) {
563
+ if (this.config.environment === "development") {
477
564
  console.error("[MCP-I] Checking tool protection:", {
478
565
  tool: toolName,
479
566
  agentDid: identity.did.slice(0, 20) + "...",
@@ -532,7 +619,7 @@ export class MCPIRuntimeBase {
532
619
  // Clean up expired intercepted calls periodically
533
620
  this.cleanupExpiredInterceptedCalls();
534
621
 
535
- if (this.config.audit?.enabled) {
622
+ if (this.config.environment === "development") {
536
623
  console.warn(
537
624
  "[MCP-I] BLOCKED: Tool requires delegation but none provided",
538
625
  {
@@ -572,11 +659,11 @@ export class MCPIRuntimeBase {
572
659
  const consentProof = session?.consentProof;
573
660
 
574
661
  if (!this.accessControlService) {
575
- // Access control service not available - log warning but allow execution
576
- // This enables graceful degradation when service is not configured
577
- if (this.config.audit?.enabled) {
662
+ // A presented credential is not authority by itself. If the verifier
663
+ // is unavailable, fail closed before the protected handler executes.
664
+ if (this.config.environment === "development") {
578
665
  console.warn(
579
- "[MCP-I] ⚠️ Delegation token provided but AccessControlApiService not configured - skipping verification",
666
+ "[MCP-I] Delegation verifier unavailable - blocking protected tool",
580
667
  {
581
668
  tool: toolName,
582
669
  agentDid: identity.did.slice(0, 20) + "...",
@@ -585,10 +672,35 @@ export class MCPIRuntimeBase {
585
672
  }
586
673
  );
587
674
  }
675
+ const interceptedCall: InterceptedToolCall = {
676
+ toolName,
677
+ args,
678
+ sessionId: session?.id || "unknown",
679
+ timestamp: this.clock.now(),
680
+ expiresAt: this.clock.calculateExpiry(1800),
681
+ };
682
+ const resumeToken = await this.generateResumeToken(interceptedCall);
683
+ const consentUrl = this.buildConsentUrl(
684
+ toolName,
685
+ protection.requiredScopes,
686
+ session,
687
+ resumeToken,
688
+ undefined,
689
+ this.getConsentProvider(protection)
690
+ );
691
+ this.interceptedCalls.set(resumeToken, interceptedCall);
692
+ this.cleanupExpiredInterceptedCalls();
693
+ throw new DelegationRequiredError(
694
+ toolName,
695
+ protection.requiredScopes,
696
+ consentUrl,
697
+ interceptedCall,
698
+ resumeToken
699
+ );
588
700
  } else {
589
701
  // Verify delegation token with AccessControlApiService
590
702
  try {
591
- if (this.config.audit?.enabled) {
703
+ if (this.config.environment === "development") {
592
704
  console.error(
593
705
  "[MCP-I] 🔐 Verifying delegation token with AccessControlApiService",
594
706
  {
@@ -612,7 +724,7 @@ export class MCPIRuntimeBase {
612
724
  // Without user_did, AgentShield cannot validate user isolation
613
725
  if (session?.userDid) {
614
726
  verifyRequest.user_did = session.userDid;
615
- if (this.config.audit?.enabled) {
727
+ if (this.config.environment === "development") {
616
728
  console.error(
617
729
  "[MCP-I] 🔐 Including user_did in verification request",
618
730
  {
@@ -656,7 +768,7 @@ export class MCPIRuntimeBase {
656
768
  "Delegation token invalid or expired";
657
769
  const errorDetails = verificationResult.data.error;
658
770
 
659
- if (this.config.audit?.enabled) {
771
+ if (this.config.environment === "development") {
660
772
  console.error("[MCP-I] ❌ Delegation verification FAILED", {
661
773
  tool: toolName,
662
774
  agentDid: identity.did.slice(0, 20) + "...",
@@ -726,7 +838,7 @@ export class MCPIRuntimeBase {
726
838
  // User identifier mismatch - potential security issue
727
839
  const securityError = `Delegation user_identifier mismatch: delegation has "${delegationUserIdentifier.substring(0, 20)}..." but session has "${sessionUserDid.substring(0, 20)}..."`;
728
840
 
729
- if (this.config.audit?.enabled) {
841
+ if (this.config.environment === "development") {
730
842
  console.error(
731
843
  "[MCP-I] 🔒 SECURITY: User identifier validation FAILED",
732
844
  {
@@ -778,7 +890,7 @@ export class MCPIRuntimeBase {
778
890
  }
779
891
 
780
892
  // User identifier validation passed (direct match or trusted AgentShield verification)
781
- if (this.config.audit?.enabled) {
893
+ if (this.config.environment === "development") {
782
894
  console.error("[MCP-I] ✅ User identifier validation PASSED", {
783
895
  tool: toolName,
784
896
  agentDid: identity.did.slice(0, 20) + "...",
@@ -794,7 +906,7 @@ export class MCPIRuntimeBase {
794
906
  }
795
907
  } else if (delegationUserIdentifier && !sessionUserDid) {
796
908
  // Delegation has user_identifier but session doesn't - log warning
797
- if (this.config.audit?.enabled) {
909
+ if (this.config.environment === "development") {
798
910
  console.warn(
799
911
  "[MCP-I] ⚠️ Delegation has user_identifier but session missing userDid",
800
912
  {
@@ -824,7 +936,7 @@ export class MCPIRuntimeBase {
824
936
  // If tool requires authorization but credential doesn't have auth data, reject
825
937
  // This prevents bypassing auth checks with incomplete credential data
826
938
  if (!delegationAuth) {
827
- if (this.config.audit?.enabled) {
939
+ if (this.config.environment === "development") {
828
940
  console.error(
829
941
  "[MCP-I] ❌ Tool requires authorization but credential missing auth data",
830
942
  {
@@ -881,7 +993,7 @@ export class MCPIRuntimeBase {
881
993
  : "";
882
994
  const authMismatchReason = `Authorization method mismatch: delegation has ${delegationAuth.type}${delegationAuth.provider ? `:${delegationAuth.provider}` : ""}${delegationAuth.credentialType ? `:${delegationAuth.credentialType}` : ""} but tool requires ${toolAuth.type}${toolAuthProvider}${toolAuthCredentialType}`;
883
995
 
884
- if (this.config.audit?.enabled) {
996
+ if (this.config.environment === "development") {
885
997
  console.error(
886
998
  "[MCP-I] ❌ Authorization method validation FAILED",
887
999
  {
@@ -927,7 +1039,7 @@ export class MCPIRuntimeBase {
927
1039
  }
928
1040
 
929
1041
  // Authorization method validation passed
930
- if (this.config.audit?.enabled) {
1042
+ if (this.config.environment === "development") {
931
1043
  console.error(
932
1044
  "[MCP-I] ✅ Authorization method validation PASSED",
933
1045
  {
@@ -942,7 +1054,7 @@ export class MCPIRuntimeBase {
942
1054
  // If credential is missing entirely (KV/Memory verifiers), skip validation for backward compatibility
943
1055
 
944
1056
  // Verification succeeded
945
- if (this.config.audit?.enabled) {
1057
+ if (this.config.environment === "development") {
946
1058
  console.error("[MCP-I] ✅ Delegation verification SUCCEEDED", {
947
1059
  tool: toolName,
948
1060
  agentDid: identity.did.slice(0, 20) + "...",
@@ -960,7 +1072,7 @@ export class MCPIRuntimeBase {
960
1072
 
961
1073
  // Handle AgentShieldAPIError (network errors, API errors, etc.)
962
1074
  if (error instanceof AgentShieldAPIError) {
963
- if (this.config.audit?.enabled) {
1075
+ if (this.config.environment === "development") {
964
1076
  console.error(
965
1077
  "[MCP-I] ❌ Delegation verification error (API failure)",
966
1078
  {
@@ -1007,7 +1119,7 @@ export class MCPIRuntimeBase {
1007
1119
  }
1008
1120
 
1009
1121
  // Unexpected error - log and fail securely
1010
- if (this.config.audit?.enabled) {
1122
+ if (this.config.environment === "development") {
1011
1123
  console.error(
1012
1124
  "[MCP-I] ❌ Unexpected error during delegation verification",
1013
1125
  {
@@ -1052,7 +1164,7 @@ export class MCPIRuntimeBase {
1052
1164
  }
1053
1165
  } else {
1054
1166
  // No protection required - tool can be executed freely
1055
- if (this.config.audit?.enabled) {
1167
+ if (this.config.environment === "development") {
1056
1168
  console.error(
1057
1169
  "[MCP-I] Tool protection check passed (no delegation required)",
1058
1170
  {
@@ -1075,8 +1187,8 @@ export class MCPIRuntimeBase {
1075
1187
  this.lastProof = proof;
1076
1188
 
1077
1189
  // Log if audit is enabled
1078
- if (this.config.audit?.enabled) {
1079
- this.logAudit("tool_executed", {
1190
+ if (this.config.environment === "development") {
1191
+ this.emitDiagnostic("tool_executed", {
1080
1192
  tool: toolName,
1081
1193
  sessionId: session?.id,
1082
1194
  timestamp: this.clock.now(),
@@ -1885,15 +1997,6 @@ export class MCPIRuntimeBase {
1885
1997
  };
1886
1998
  }
1887
1999
 
1888
- /**
1889
- * Get audit logger
1890
- */
1891
- getAuditLogger(): RuntimeAuditLogger | undefined {
1892
- return {
1893
- log: (event: string, data: unknown) => this.logAudit(event, data),
1894
- };
1895
- }
1896
-
1897
2000
  /**
1898
2001
  * Rotate keys
1899
2002
  */
@@ -1902,8 +2005,8 @@ export class MCPIRuntimeBase {
1902
2005
  const newIdentity = await this.identity.rotateKeys();
1903
2006
  this.cachedIdentity = newIdentity;
1904
2007
 
1905
- if (this.config.audit?.enabled) {
1906
- this.logAudit("keys_rotated", {
2008
+ if (this.config.environment === "development") {
2009
+ this.emitDiagnostic("keys_rotated", {
1907
2010
  oldDid: oldDid,
1908
2011
  newDid: newIdentity.did,
1909
2012
  timestamp: this.clock.now(),
@@ -1946,62 +2049,14 @@ export class MCPIRuntimeBase {
1946
2049
  return `${SESSION_ID_PREFIX}${uuid}`;
1947
2050
  }
1948
2051
 
1949
- /**
1950
- * Log structured events in JSON format (NOT frozen audit format).
1951
- *
1952
- * **Important:** This method logs events in JSON format for general runtime events
1953
- * (e.g., "runtime_initialized", "tool_executed", "keys_rotated").
1954
- *
1955
- * **For frozen format audit logs** (MCP-I spec compliance), use `AuditLogger.logAuditRecord()`
1956
- * from `@kya-os/mcp-i/runtime` instead. The frozen format is:
1957
- * ```
1958
- * audit.v1 ts=<unix> session=<id> audience=<host> did=<did> kid=<kid> reqHash=<sha256:..> resHash=<sha256:..> verified=yes|no scope=<scopeId|->
1959
- * ```
1960
- *
1961
- * **Format:** JSON object with `event`, `data`, `timestamp`, and `timestampFormatted` fields.
1962
- *
1963
- * **Privacy:** If `includePayloads` is false (default), the `data` field is omitted.
1964
- *
1965
- * **Use Cases:**
1966
- * - Developer debugging and local logging
1967
- * - Runtime initialization events
1968
- * - Tool execution tracking (non-spec-compliant)
1969
- * - Key rotation events
1970
- *
1971
- * **NOT for:**
1972
- * - MCP-I spec-compliant audit logs (use `AuditLogger`)
1973
- * - Production audit trails (use `AuditLogger`)
1974
- * - Compliance requirements (use `AuditLogger`)
1975
- *
1976
- * @param event - Event name (e.g., "runtime_initialized", "tool_executed")
1977
- * @param data - Event data (only included if `includePayloads` is true)
1978
- *
1979
- * @example
1980
- * ```typescript
1981
- * // Logs: {"event":"runtime_initialized","timestamp":1234567890,"timestampFormatted":"2024-01-01T00:00:00Z"}
1982
- * this.logAudit("runtime_initialized", { did: "did:key:..." });
1983
- * ```
1984
- *
1985
- * @internal This is a private method for internal runtime events.
1986
- * Use AuditLogger for spec-compliant frozen format audit logs.
1987
- */
1988
- private logAudit(event: string, data: unknown): void {
1989
- if (!this.config.audit?.enabled) return;
1990
-
1991
- const record = {
2052
+ /** Development-only diagnostics. These records make no audit assurance claim. */
2053
+ private emitDiagnostic(event: string, data: unknown): void {
2054
+ if (this.config.environment !== "development") return;
2055
+ console.error("[MCP-I diagnostic]", JSON.stringify({
1992
2056
  event,
1993
- data: this.config.audit.includePayloads ? data : undefined,
2057
+ data,
1994
2058
  timestamp: this.clock.now(),
1995
- timestampFormatted: this.clock.format(this.clock.now()),
1996
- };
1997
-
1998
- const logLine = JSON.stringify(record);
1999
-
2000
- if (this.config.audit.logFunction) {
2001
- this.config.audit.logFunction(logLine);
2002
- } else {
2003
- console.error("[AUDIT]", logLine);
2004
- }
2059
+ }));
2005
2060
  }
2006
2061
 
2007
2062
  private createDIDDocument(identity: AgentIdentity): DIDDocument {
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Tests for auth-type-satisfies
3
+ *
4
+ * Covers the strict-normalized-equality decision (locked 2026-07-29) for the
5
+ * consent-approve auth-gate security fix:
6
+ * - the demonstrated bug case (a `none` delegation must not satisfy a typed
7
+ * requirement)
8
+ * - happy-path equality across all canonical types
9
+ * - deprecated-alias folding (`oauth` -> `oauth2`, `credential` ->
10
+ * `verifiable_credential`)
11
+ * - non-interchangeability of distinct typed requirements
12
+ * - nullish/fail-safe handling on both sides
13
+ * - a full cross-product table across all 10 canonical authorization types
14
+ * (`AUTHORIZATION_TYPES`, contracts/src/tool-protection/index.ts ~88-106),
15
+ * checked against an independently-defined normalization oracle (not the
16
+ * implementation under test) so the table isn't tautological.
17
+ */
18
+
19
+ import { describe, it, expect } from "vitest";
20
+ import { authTypeSatisfies, normalizeAuthType } from "../auth-type-satisfies";
21
+
22
+ describe("normalizeAuthType", () => {
23
+ it("returns undefined for undefined", () => {
24
+ expect(normalizeAuthType(undefined)).toBeUndefined();
25
+ });
26
+
27
+ it("returns undefined for null", () => {
28
+ expect(normalizeAuthType(null)).toBeUndefined();
29
+ });
30
+
31
+ it("returns undefined for an empty/whitespace-only string", () => {
32
+ expect(normalizeAuthType("")).toBeUndefined();
33
+ expect(normalizeAuthType(" ")).toBeUndefined();
34
+ });
35
+
36
+ it("folds the deprecated 'oauth' alias to 'oauth2'", () => {
37
+ expect(normalizeAuthType("oauth")).toBe("oauth2");
38
+ });
39
+
40
+ it("folds the deprecated 'credential' alias to 'verifiable_credential'", () => {
41
+ expect(normalizeAuthType("credential")).toBe("verifiable_credential");
42
+ });
43
+
44
+ it("leaves canonical types unchanged", () => {
45
+ expect(normalizeAuthType("oauth2")).toBe("oauth2");
46
+ expect(normalizeAuthType("password")).toBe("password");
47
+ expect(normalizeAuthType("mdl")).toBe("mdl");
48
+ expect(normalizeAuthType("idv")).toBe("idv");
49
+ expect(normalizeAuthType("verifiable_credential")).toBe(
50
+ "verifiable_credential"
51
+ );
52
+ expect(normalizeAuthType("webauthn")).toBe("webauthn");
53
+ expect(normalizeAuthType("siwe")).toBe("siwe");
54
+ expect(normalizeAuthType("apikey")).toBe("apikey");
55
+ expect(normalizeAuthType("none")).toBe("none");
56
+ });
57
+
58
+ it("trims and lowercases defensively", () => {
59
+ expect(normalizeAuthType(" Password ")).toBe("password");
60
+ expect(normalizeAuthType("OAUTH")).toBe("oauth2");
61
+ });
62
+ });
63
+
64
+ describe("authTypeSatisfies", () => {
65
+ describe("the bug case: a 'none' delegation must not satisfy a typed requirement", () => {
66
+ it('("none", "password") -> false', () => {
67
+ expect(authTypeSatisfies("none", "password")).toBe(false);
68
+ });
69
+
70
+ it('("none", "oauth2") -> false', () => {
71
+ expect(authTypeSatisfies("none", "oauth2")).toBe(false);
72
+ });
73
+ });
74
+
75
+ describe("happy pairs (strict equality)", () => {
76
+ it('("password", "password") -> true', () => {
77
+ expect(authTypeSatisfies("password", "password")).toBe(true);
78
+ });
79
+
80
+ it('("oauth2", "oauth2") -> true', () => {
81
+ expect(authTypeSatisfies("oauth2", "oauth2")).toBe(true);
82
+ });
83
+
84
+ it('("none", "none") -> true', () => {
85
+ expect(authTypeSatisfies("none", "none")).toBe(true);
86
+ });
87
+
88
+ it('("apikey", "apikey") -> true', () => {
89
+ expect(authTypeSatisfies("apikey", "apikey")).toBe(true);
90
+ });
91
+
92
+ it('("mdl", "mdl") -> true', () => {
93
+ expect(authTypeSatisfies("mdl", "mdl")).toBe(true);
94
+ });
95
+
96
+ it('("idv", "idv") -> true', () => {
97
+ expect(authTypeSatisfies("idv", "idv")).toBe(true);
98
+ });
99
+
100
+ it('("webauthn", "webauthn") -> true', () => {
101
+ expect(authTypeSatisfies("webauthn", "webauthn")).toBe(true);
102
+ });
103
+
104
+ it('("siwe", "siwe") -> true', () => {
105
+ expect(authTypeSatisfies("siwe", "siwe")).toBe(true);
106
+ });
107
+
108
+ it('("verifiable_credential", "verifiable_credential") -> true', () => {
109
+ expect(
110
+ authTypeSatisfies("verifiable_credential", "verifiable_credential")
111
+ ).toBe(true);
112
+ });
113
+ });
114
+
115
+ describe("alias folding", () => {
116
+ it('("oauth", "oauth2") -> true', () => {
117
+ expect(authTypeSatisfies("oauth", "oauth2")).toBe(true);
118
+ });
119
+
120
+ it('("oauth2", "oauth") -> true', () => {
121
+ expect(authTypeSatisfies("oauth2", "oauth")).toBe(true);
122
+ });
123
+
124
+ it('("oauth", "oauth") -> true', () => {
125
+ expect(authTypeSatisfies("oauth", "oauth")).toBe(true);
126
+ });
127
+
128
+ it('("credential", "verifiable_credential") -> true', () => {
129
+ expect(authTypeSatisfies("credential", "verifiable_credential")).toBe(
130
+ true
131
+ );
132
+ });
133
+
134
+ it('("verifiable_credential", "credential") -> true', () => {
135
+ expect(authTypeSatisfies("verifiable_credential", "credential")).toBe(
136
+ true
137
+ );
138
+ });
139
+
140
+ it('("credential", "credential") -> true', () => {
141
+ expect(authTypeSatisfies("credential", "credential")).toBe(true);
142
+ });
143
+ });
144
+
145
+ describe("non-interchangeable types (no stronger-satisfies-weaker lattice)", () => {
146
+ it('("oauth2", "password") -> false', () => {
147
+ expect(authTypeSatisfies("oauth2", "password")).toBe(false);
148
+ });
149
+
150
+ it('("password", "oauth2") -> false', () => {
151
+ expect(authTypeSatisfies("password", "oauth2")).toBe(false);
152
+ });
153
+
154
+ it('("verifiable_credential", "password") -> false', () => {
155
+ expect(authTypeSatisfies("verifiable_credential", "password")).toBe(
156
+ false
157
+ );
158
+ });
159
+
160
+ it('("password", "none") -> false (typed delegation does not satisfy a none-gated tool either)', () => {
161
+ expect(authTypeSatisfies("password", "none")).toBe(false);
162
+ });
163
+
164
+ it('("apikey", "webauthn") -> false', () => {
165
+ expect(authTypeSatisfies("apikey", "webauthn")).toBe(false);
166
+ });
167
+ });
168
+
169
+ describe("nullish / fail-safe handling", () => {
170
+ it('(undefined, "password") -> false', () => {
171
+ expect(authTypeSatisfies(undefined, "password")).toBe(false);
172
+ });
173
+
174
+ it('(null, "password") -> false', () => {
175
+ expect(authTypeSatisfies(null, "password")).toBe(false);
176
+ });
177
+
178
+ it('("password", undefined) -> false (documented rule: no requirement is not auto-satisfied)', () => {
179
+ expect(authTypeSatisfies("password", undefined)).toBe(false);
180
+ });
181
+
182
+ it('("password", null) -> false', () => {
183
+ expect(authTypeSatisfies("password", null)).toBe(false);
184
+ });
185
+
186
+ it("(undefined, undefined) -> false", () => {
187
+ expect(authTypeSatisfies(undefined, undefined)).toBe(false);
188
+ });
189
+
190
+ it('("", "password") -> false (empty string normalizes to undefined)', () => {
191
+ expect(authTypeSatisfies("", "password")).toBe(false);
192
+ });
193
+
194
+ it('("none", undefined) -> false', () => {
195
+ expect(authTypeSatisfies("none", undefined)).toBe(false);
196
+ });
197
+ });
198
+
199
+ describe("full cross-product table across all 10 canonical types", () => {
200
+ // Independent normalization oracle (deliberately NOT importing
201
+ // normalizeAuthType) so this table verifies authTypeSatisfies's
202
+ // behavior rather than merely restating its own implementation.
203
+ const CANONICAL_NORMALIZED: Record<string, string> = {
204
+ oauth: "oauth2",
205
+ oauth2: "oauth2",
206
+ password: "password",
207
+ mdl: "mdl",
208
+ idv: "idv",
209
+ verifiable_credential: "verifiable_credential",
210
+ webauthn: "webauthn",
211
+ siwe: "siwe",
212
+ apikey: "apikey",
213
+ none: "none",
214
+ };
215
+
216
+ const ALL_TYPES = Object.keys(CANONICAL_NORMALIZED);
217
+
218
+ for (const delegationType of ALL_TYPES) {
219
+ for (const requiredType of ALL_TYPES) {
220
+ const expected =
221
+ CANONICAL_NORMALIZED[delegationType] ===
222
+ CANONICAL_NORMALIZED[requiredType];
223
+
224
+ it(`("${delegationType}", "${requiredType}") -> ${expected}`, () => {
225
+ expect(authTypeSatisfies(delegationType, requiredType)).toBe(
226
+ expected
227
+ );
228
+ });
229
+ }
230
+ }
231
+ });
232
+ });