@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
@@ -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,47 @@
1
+ /**
2
+ * C4 (#2918) 3c envelope flip — `DelegationRequiredError` → `needs_authorization`.
3
+ *
4
+ * Projects the internal `DelegationRequiredError` control-flow signal onto the
5
+ * ratified DIF `needs_authorization` envelope so the tool-call gate can dual-emit
6
+ * the canonical wire shape alongside the legacy proprietary `_meta` keys (the
7
+ * wire-format dual-accept thesis: read accepts both; emit moves to the new form;
8
+ * legacy keys stay until the telemetry-gated sunset).
9
+ *
10
+ * Envelope-flip ONLY — N-of-M step-up (`needs_approval` / `NeedsApprovalError`)
11
+ * is deferred to the T3-edge step-up lane (#3222) and is intentionally NOT
12
+ * produced here.
13
+ *
14
+ * The shape + builder are sourced from `@kya-os/contracts/runtime` (the ratified
15
+ * source that DIF `@kya-os/mcp` mirrors) rather than `@kya-os/mcp` directly: this
16
+ * package is CommonJS (`module: Node16`) and `@kya-os/mcp` is ESM-only, so a
17
+ * static value import would not resolve from CJS. `auth/handshake.ts` already
18
+ * builds `NeedsAuthorizationError` from `@kya-os/contracts/runtime` for the same
19
+ * reason — this mirrors that convention.
20
+ */
21
+ import {
22
+ createNeedsAuthorizationError,
23
+ type NeedsAuthorizationError,
24
+ } from "@kya-os/contracts/runtime";
25
+ import type { DelegationRequiredError } from "../types/tool-protection.js";
26
+
27
+ /**
28
+ * Build the DIF `needs_authorization` envelope from a `DelegationRequiredError`.
29
+ *
30
+ * @param err - the thrown delegation signal (already carries `consentUrl`,
31
+ * `resumeToken`, and `requiredScopes` populated at every throw site).
32
+ * @param expiresAtMs - resume-token expiry as **milliseconds since epoch**, the
33
+ * unit the contracts schema expects and that `clock.calculateExpiry()` returns
34
+ * (`now() + ttlSeconds * 1000`). Pass `interceptedCall.expiresAt` directly.
35
+ */
36
+ export function toNeedsAuthorization(
37
+ err: DelegationRequiredError,
38
+ expiresAtMs: number
39
+ ): NeedsAuthorizationError {
40
+ return createNeedsAuthorizationError({
41
+ message: `Authorization required for tool "${err.toolName}".`,
42
+ authorizationUrl: err.consentUrl ?? "",
43
+ resumeToken: err.resumeToken ?? "",
44
+ expiresAt: expiresAtMs,
45
+ scopes: err.requiredScopes,
46
+ });
47
+ }
@@ -170,6 +170,72 @@ describe("OAuthConfigService", () => {
170
170
  expect(result.configuredProvider).toBe("github");
171
171
  });
172
172
 
173
+ it("maps provider metadata.clientSecretName (registry-model secret reference)", async () => {
174
+ // Regression: the parser previously dropped `metadata`, so
175
+ // OAuthService.resolveClientSecret could not resolve a confidential
176
+ // provider's secret from secure storage (it keys off
177
+ // `metadata.clientSecretName`). It then fell back to the inline
178
+ // `clientSecret` — which the AgentShield /providers response
179
+ // intentionally OMITS — so the worker sent an empty secret and the
180
+ // OAuth token exchange failed with "client_id and/or client_secret
181
+ // incorrect".
182
+ const apiResponse = {
183
+ success: true,
184
+ data: {
185
+ providers: {
186
+ github: {
187
+ clientId: "gh-id",
188
+ // clientSecret intentionally omitted by the /providers route
189
+ authorizationUrl: "https://github.com/login/oauth/authorize",
190
+ tokenUrl: "https://github.com/login/oauth/access_token",
191
+ scopes: [],
192
+ metadata: {
193
+ clientSecretName: "KYA_PROD_ACME_ABCD1234_GITHUB_CLIENT_SECRET",
194
+ clientSecretVersion: 3,
195
+ },
196
+ },
197
+ // snake_case metadata must be normalized to camelCase
198
+ google: {
199
+ client_id: "g-id",
200
+ authorization_url: "https://accounts.google.com/o/oauth2/v2/auth",
201
+ token_url: "https://oauth2.googleapis.com/token",
202
+ metadata: {
203
+ client_secret_name: "KYA_PROD_ACME_ABCD1234_GOOGLE_CLIENT_SECRET",
204
+ },
205
+ },
206
+ },
207
+ configuredProvider: "github",
208
+ },
209
+ };
210
+ (mockFetchProvider.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
211
+ ok: true,
212
+ status: 200,
213
+ json: async () => apiResponse,
214
+ });
215
+
216
+ const service = new OAuthConfigService({
217
+ baseUrl: "https://api.example.com",
218
+ apiKey: "test-api-key",
219
+ fetchProvider: mockFetchProvider,
220
+ cache: mockCache,
221
+ });
222
+
223
+ const result = await service.getOAuthConfig("proj-123");
224
+
225
+ // The secret NAME reference must survive parsing so resolveClientSecret
226
+ // can resolve the actual secret from secure storage (worker env binding).
227
+ expect(result.providers.github.metadata?.clientSecretName).toBe(
228
+ "KYA_PROD_ACME_ABCD1234_GITHUB_CLIENT_SECRET"
229
+ );
230
+ expect(result.providers.github.metadata?.clientSecretVersion).toBe(3);
231
+ // clientSecret stays null (API omits it): resolution must come via metadata.
232
+ expect(result.providers.github.clientSecret).toBeNull();
233
+ // snake_case metadata is normalized to camelCase.
234
+ expect(result.providers.google.metadata?.clientSecretName).toBe(
235
+ "KYA_PROD_ACME_ABCD1234_GOOGLE_CLIENT_SECRET"
236
+ );
237
+ });
238
+
173
239
  it("should cache fetched config", async () => {
174
240
  const service = new OAuthConfigService({
175
241
  baseUrl: "https://api.example.com",
@@ -35,7 +35,7 @@ describe("ProofVerifier Integration - Real DID Resolution", () => {
35
35
  };
36
36
 
37
37
  const createValidProof = (did: string, kid: string): DetachedProof => {
38
- const header = { alg: "EdDSA", typ: "JWT" };
38
+ const header = { alg: "EdDSA", typ: "JWT", kid };
39
39
  const payload = {
40
40
  aud: "test-audience",
41
41
  sub: did,
@@ -39,7 +39,11 @@ describe('ProofVerifier Security', () => {
39
39
  };
40
40
 
41
41
  const createValidProof = (): DetachedProof => {
42
- const header = { alg: 'EdDSA', typ: 'JWT' };
42
+ const header = {
43
+ alg: 'EdDSA',
44
+ typ: 'JWT',
45
+ kid: 'did:key:z123#key-1',
46
+ };
43
47
  // Create a proper JSON payload that matches the meta structure
44
48
  const payload = {
45
49
  aud: 'test-audience',
@@ -253,7 +257,7 @@ describe('ProofVerifier Security', () => {
253
257
  });
254
258
 
255
259
  it('should handle detached JWS reconstruction', async () => {
256
- const header = { alg: 'EdDSA' };
260
+ const header = { alg: 'EdDSA', kid: 'did:key:z123#key-1' };
257
261
  const headerB64 = btoa(JSON.stringify(header))
258
262
  .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
259
263
  const signatureB64 = btoa('signature')
@@ -486,4 +490,3 @@ describe('ProofVerifier Security', () => {
486
490
  });
487
491
  });
488
492
  });
489
-
@@ -8,10 +8,44 @@
8
8
  */
9
9
 
10
10
  import type { FetchProvider } from "../providers/base.js";
11
- import type { OAuthConfig, OAuthProvider } from "@kya-os/contracts/config";
11
+ import type {
12
+ OAuthConfig,
13
+ OAuthProvider,
14
+ OAuthProviderSecretMetadata,
15
+ } from "@kya-os/contracts/config";
12
16
  import type { OAuthConfigCache } from "../cache/oauth-config-cache.js";
13
17
  import { InMemoryOAuthConfigCache } from "../cache/oauth-config-cache.js";
14
18
 
19
+ /**
20
+ * Normalize a provider's secret-reference metadata from the AgentShield
21
+ * `/providers` response into the OAuthProvider `metadata` shape.
22
+ *
23
+ * The response may use camelCase or snake_case; only the secret-*name*
24
+ * references are carried (never the secret values). Returns `undefined` when
25
+ * no metadata is present so the field stays absent on the parsed provider.
26
+ */
27
+ function mapProviderSecretMetadata(
28
+ raw: unknown
29
+ ): OAuthProviderSecretMetadata | undefined {
30
+ if (!raw || typeof raw !== "object") return undefined;
31
+ const m = raw as Record<string, unknown>;
32
+ const metadata: OAuthProviderSecretMetadata = {
33
+ clientSecretName: (m.clientSecretName ?? m.client_secret_name) as
34
+ | string
35
+ | undefined,
36
+ clientIdSecretName: (m.clientIdSecretName ?? m.client_id_secret_name) as
37
+ | string
38
+ | undefined,
39
+ apiKeySecretName: (m.apiKeySecretName ?? m.api_key_secret_name) as
40
+ | string
41
+ | undefined,
42
+ clientSecretVersion: (m.clientSecretVersion ?? m.client_secret_version) as
43
+ | number
44
+ | undefined,
45
+ };
46
+ return metadata;
47
+ }
48
+
15
49
  export interface OAuthConfigServiceConfig {
16
50
  /** Base URL for AgentShield API (e.g., "https://kya.vouched.id") */
17
51
  baseUrl: string;
@@ -136,6 +170,15 @@ export class OAuthConfigService {
136
170
  tokenEndpointAuthMethod: (p.tokenEndpointAuthMethod ?? p.token_endpoint_auth_method) as "client_secret_post" | "client_secret_basic" | undefined,
137
171
  responseType: (p.responseType ?? p.response_type) as string | undefined,
138
172
  grantType: (p.grantType ?? p.grant_type) as string | undefined,
173
+ // Provider-registry secret metadata (clientSecretName etc.). REQUIRED:
174
+ // OAuthService.resolveClientSecret resolves a confidential provider's
175
+ // client secret from secure storage via `metadata.clientSecretName`
176
+ // (the AgentShield /providers response intentionally omits the plaintext
177
+ // `clientSecret`). Without mapping this field here, `metadata` is
178
+ // undefined, resolveClientSecret falls back to the (absent) inline
179
+ // clientSecret, and the worker sends an empty secret — token exchange
180
+ // then fails with "client_id and/or client_secret incorrect".
181
+ metadata: mapProviderSecretMetadata(p.metadata),
139
182
  };
140
183
  }
141
184