@kya-os/mcp-i-runtime 1.2.5 → 1.3.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 (116) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/types.d.ts +2 -2
  3. package/dist/auth/types.d.ts.map +1 -1
  4. package/dist/config/remote-config.d.ts +3 -3
  5. package/dist/config/remote-config.js +6 -6
  6. package/dist/config/remote-config.js.map +1 -1
  7. package/dist/identity/user-did-manager.d.ts +4 -4
  8. package/dist/identity/user-did-manager.js +5 -5
  9. package/dist/identity/user-did-manager.js.map +1 -1
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +11 -3
  13. package/dist/index.js.map +1 -1
  14. package/dist/runtime/audit.d.ts.map +1 -1
  15. package/dist/runtime/audit.js +22 -0
  16. package/dist/runtime/audit.js.map +1 -1
  17. package/dist/runtime/base.d.ts +14 -11
  18. package/dist/runtime/base.d.ts.map +1 -1
  19. package/dist/runtime/base.js +51 -29
  20. package/dist/runtime/base.js.map +1 -1
  21. package/dist/runtime/delegation-denial.d.ts +43 -0
  22. package/dist/runtime/delegation-denial.d.ts.map +1 -0
  23. package/dist/runtime/delegation-denial.js +83 -0
  24. package/dist/runtime/delegation-denial.js.map +1 -0
  25. package/dist/runtime/verified-delegation.d.ts +30 -0
  26. package/dist/runtime/verified-delegation.d.ts.map +1 -0
  27. package/dist/runtime/verified-delegation.js +62 -0
  28. package/dist/runtime/verified-delegation.js.map +1 -0
  29. package/dist/services/access-control.service.d.ts +4 -4
  30. package/dist/services/access-control.service.d.ts.map +1 -1
  31. package/dist/services/access-control.service.js +34 -34
  32. package/dist/services/access-control.service.js.map +1 -1
  33. package/dist/services/delegation-error-formatter.d.ts +15 -0
  34. package/dist/services/delegation-error-formatter.d.ts.map +1 -1
  35. package/dist/services/delegation-error-formatter.js +27 -1
  36. package/dist/services/delegation-error-formatter.js.map +1 -1
  37. package/dist/services/oauth-config.service.d.ts +4 -4
  38. package/dist/services/oauth-config.service.d.ts.map +1 -1
  39. package/dist/services/oauth-config.service.js +8 -8
  40. package/dist/services/oauth-config.service.js.map +1 -1
  41. package/dist/services/oauth-provider-registry.d.ts +6 -4
  42. package/dist/services/oauth-provider-registry.d.ts.map +1 -1
  43. package/dist/services/oauth-provider-registry.js +9 -5
  44. package/dist/services/oauth-provider-registry.js.map +1 -1
  45. package/dist/services/oauth-service.d.ts +17 -10
  46. package/dist/services/oauth-service.d.ts.map +1 -1
  47. package/dist/services/oauth-service.js +14 -14
  48. package/dist/services/oauth-service.js.map +1 -1
  49. package/dist/services/oauth-token-retrieval.service.d.ts +6 -6
  50. package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -1
  51. package/dist/services/oauth-token-retrieval.service.js +5 -5
  52. package/dist/services/provider-resolver.d.ts +1 -1
  53. package/dist/services/provider-resolver.js +7 -7
  54. package/dist/services/provider-resolver.js.map +1 -1
  55. package/dist/services/session-registration.service.d.ts +5 -5
  56. package/dist/services/session-registration.service.d.ts.map +1 -1
  57. package/dist/services/session-registration.service.js +9 -9
  58. package/dist/services/session-registration.service.js.map +1 -1
  59. package/dist/services/tool-protection.service.d.ts +15 -15
  60. package/dist/services/tool-protection.service.js +18 -18
  61. package/dist/services/tool-protection.service.js.map +1 -1
  62. package/dist/types/tool-protection.d.ts +11 -4
  63. package/dist/types/tool-protection.d.ts.map +1 -1
  64. package/dist/types/tool-protection.js +8 -1
  65. package/dist/types/tool-protection.js.map +1 -1
  66. package/package.json +3 -3
  67. package/src/__tests__/config/provider-runtime-config.test.ts +1 -1
  68. package/src/__tests__/config.test.ts +3 -3
  69. package/src/__tests__/index.test.ts +12 -0
  70. package/src/__tests__/integration/full-flow.test.ts +4 -4
  71. package/src/__tests__/regression/phase2-regression.test.ts +2 -2
  72. package/src/__tests__/runtime/audit-contracts-compat.test.ts +54 -0
  73. package/src/__tests__/runtime/audit.test.ts +172 -0
  74. package/src/__tests__/runtime/delegation-denial.test.ts +115 -0
  75. package/src/__tests__/runtime/process-tool-call-security.test.ts +326 -9
  76. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +25 -10
  77. package/src/__tests__/runtime/verified-delegation.test.ts +129 -0
  78. package/src/__tests__/services/access-control-retry.test.ts +2 -2
  79. package/src/__tests__/services/cache-busting.test.ts +1 -1
  80. package/src/__tests__/services/{agentshield-integration.test.ts → checkpoint-integration.test.ts} +3 -3
  81. package/src/__tests__/services/former-names.test.ts +114 -0
  82. package/src/__tests__/services/oauth-service-errors.test.ts +5 -5
  83. package/src/__tests__/services/oauth-service-pkce.test.ts +2 -2
  84. package/src/__tests__/services/oauth-service-secret-resolution.test.ts +15 -15
  85. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +11 -11
  86. package/src/__tests__/services/tool-protection.service.test.ts +1 -1
  87. package/src/auth/types.ts +2 -2
  88. package/src/config/remote-config.ts +6 -6
  89. package/src/identity/user-did-manager.ts +5 -5
  90. package/src/index.ts +15 -0
  91. package/src/runtime/audit.ts +26 -0
  92. package/src/runtime/base.ts +63 -32
  93. package/src/runtime/delegation-denial.ts +107 -0
  94. package/src/runtime/verified-delegation.ts +66 -0
  95. package/src/services/__tests__/access-control.integration.test.ts +3 -3
  96. package/src/services/__tests__/access-control.proof-response-validation.test.ts +15 -15
  97. package/src/services/__tests__/access-control.service.test.ts +14 -14
  98. package/src/services/__tests__/delegation-error-formatter.test.ts +156 -0
  99. package/src/services/__tests__/oauth-config.service.test.ts +2 -2
  100. package/src/services/__tests__/oauth-provider-registry.test.ts +11 -11
  101. package/src/services/__tests__/provider-resolution.integration.test.ts +6 -6
  102. package/src/services/__tests__/provider-resolver.test.ts +1 -1
  103. package/src/services/__tests__/session-registration.service.test.ts +1 -1
  104. package/src/services/access-control.service.ts +31 -31
  105. package/src/services/delegation-error-formatter.ts +42 -1
  106. package/src/services/oauth-config.service.d.ts +4 -4
  107. package/src/services/oauth-config.service.ts +9 -9
  108. package/src/services/oauth-provider-registry.d.ts +4 -2
  109. package/src/services/oauth-provider-registry.ts +10 -5
  110. package/src/services/oauth-service.ts +30 -19
  111. package/src/services/oauth-token-retrieval.service.ts +8 -8
  112. package/src/services/provider-resolver.ts +7 -7
  113. package/src/services/session-registration.service.ts +10 -10
  114. package/src/services/tool-protection.service.ts +19 -19
  115. package/src/types/tool-protection.ts +13 -4
  116. package/vitest.config.mts +1 -1
@@ -29,8 +29,14 @@ import type {
29
29
  } from "@kya-os/contracts/well-known";
30
30
  import type { AccessControlApiService } from "../services/access-control.service.js";
31
31
  import { authorizationMatches } from "../services/access-control.service.js";
32
- import type { VerifyDelegationRequest } from "@kya-os/contracts/agentshield-api";
33
- import { AgentShieldAPIError } from "@kya-os/contracts/agentshield-api";
32
+ import type { VerifyDelegationRequest } from "@kya-os/contracts/checkpoint-api";
33
+ import { CheckpointAPIError } from "@kya-os/contracts/checkpoint-api";
34
+ import type { VerifiedDelegation } from "@kya-os/contracts/config";
35
+ import { toVerifiedDelegation } from "./verified-delegation.js";
36
+ import {
37
+ nativeBindingDenial,
38
+ toDelegationDenial,
39
+ } from "./delegation-denial.js";
34
40
 
35
41
  // Import the new provider runtime config
36
42
  import type { ProviderRuntimeConfig } from "../config";
@@ -248,7 +254,7 @@ export class MCPIRuntimeBase {
248
254
  *
249
255
  * Phase 5: Anonymous Sessions Until OAuth
250
256
  * - Sessions start anonymous (no userDid) unless OAuth identity provided
251
- * - User DID is resolved via AgentShield after OAuth completes
257
+ * - User DID is resolved via Checkpoint after OAuth completes
252
258
  * - Eliminates DID fragmentation (same user = same DID across sessions)
253
259
  *
254
260
  * @param request - Handshake request object (may include oauthIdentity for persistent user DID lookup)
@@ -386,11 +392,11 @@ export class MCPIRuntimeBase {
386
392
  /**
387
393
  * Update session identity after OAuth resolution (Phase 5)
388
394
  *
389
- * Called after AgentShield identity/resolve returns a persistent user DID.
395
+ * Called after Checkpoint identity/resolve returns a persistent user DID.
390
396
  * Updates the session to authenticated state with the resolved DID.
391
397
  *
392
398
  * @param sessionId - MCP session ID
393
- * @param userDid - Persistent user DID from AgentShield
399
+ * @param userDid - Persistent user DID from Checkpoint
394
400
  * @param oauthIdentity - OAuth identity information
395
401
  * @throws Error if session not found
396
402
  */
@@ -484,13 +490,15 @@ export class MCPIRuntimeBase {
484
490
  *
485
491
  * @param toolName - Name of the tool being called
486
492
  * @param args - Tool arguments
487
- * @param handler - Tool execution handler
493
+ * @param handler - Tool execution handler. A protected tool whose verifier
494
+ * returned a credential also receives the verified delegation for THIS
495
+ * call as a second argument; every other call passes `args` only.
488
496
  * @param session - Session context (expected fields: id, audience, nonce?, delegationToken?, consentProof?)
489
497
  */
490
498
  async processToolCall<TArgs = unknown, TResult = unknown>(
491
499
  toolName: string,
492
500
  args: TArgs,
493
- handler: (args: TArgs) => Promise<TResult>,
501
+ handler: (args: TArgs, verified?: VerifiedDelegation) => Promise<TResult>,
494
502
  session?: RuntimeSessionContext
495
503
  ): Promise<TResult | RuntimeRecord> {
496
504
  const auditInvocation = this.config.auditTrail
@@ -555,9 +563,13 @@ export class MCPIRuntimeBase {
555
563
  private async processToolCallInternal<TArgs = unknown, TResult = unknown>(
556
564
  toolName: string,
557
565
  args: TArgs,
558
- handler: (args: TArgs) => Promise<TResult>,
566
+ handler: (args: TArgs, verified?: VerifiedDelegation) => Promise<TResult>,
559
567
  session?: RuntimeSessionContext
560
568
  ): Promise<TResult | RuntimeRecord> {
569
+ // Set only after every check below passes. Local to this call, so
570
+ // concurrent calls on the same runtime never see each other's grant.
571
+ let verifiedDelegation: VerifiedDelegation | undefined;
572
+
561
573
  // Check tool protection (delegation requirement)
562
574
  if (this.config.toolProtectionService) {
563
575
  // Get agent identity to check protection
@@ -724,7 +736,7 @@ export class MCPIRuntimeBase {
724
736
 
725
737
  // ✅ CRITICAL: Include user_did for user-scoped delegation verification
726
738
  // This prevents cross-user delegation leakage (Priority 3 fallback issue)
727
- // Without user_did, AgentShield cannot validate user isolation
739
+ // Without user_did, Checkpoint cannot validate user isolation
728
740
  if (session?.userDid) {
729
741
  verifyRequest.user_did = session.userDid;
730
742
  if (this.config.environment === "development") {
@@ -766,7 +778,10 @@ export class MCPIRuntimeBase {
766
778
  // A native admission binds this exact request to a holder. Recheck
767
779
  // the returned authority rather than accepting a valid response for
768
780
  // another principal or a weaker scope set from a stale adapter.
781
+ // Only an accepted grant carries a credential to compare. A refused
782
+ // grant has none, so it keeps the verifier's own denial code.
769
783
  const nativeBindingMismatch =
784
+ verificationResult.data.valid === true &&
770
785
  session?.verifiedInvokerDid !== undefined &&
771
786
  (verificationResult.data.credential?.agent_did !==
772
787
  session.verifiedInvokerDid ||
@@ -781,6 +796,13 @@ export class MCPIRuntimeBase {
781
796
  : verificationResult.data.reason) ||
782
797
  "Delegation token invalid or expired";
783
798
  const errorDetails = verificationResult.data.error;
799
+ // Machine-readable reason from the allowlist only. Upstream
800
+ // message and details never reach the client or the ledger.
801
+ const denial = nativeBindingMismatch
802
+ ? nativeBindingDenial()
803
+ : toDelegationDenial(
804
+ errorDetails?.code ?? verificationResult.data.reason
805
+ );
784
806
 
785
807
  if (this.config.environment === "development") {
786
808
  console.error("[MCP-I] ❌ Delegation verification FAILED", {
@@ -789,6 +811,7 @@ export class MCPIRuntimeBase {
789
811
  reason,
790
812
  errorCode: errorDetails?.code,
791
813
  errorMessage: errorDetails?.message,
814
+ denialCode: denial?.code,
792
815
  requiredScopes: protection.requiredScopes,
793
816
  });
794
817
  }
@@ -821,7 +844,8 @@ export class MCPIRuntimeBase {
821
844
  protection.requiredScopes,
822
845
  consentUrl,
823
846
  interceptedCall,
824
- resumeToken
847
+ resumeToken,
848
+ denial
825
849
  );
826
850
  }
827
851
 
@@ -829,7 +853,7 @@ export class MCPIRuntimeBase {
829
853
  // This ensures delegations are user-specific and prevents user isolation bypass
830
854
  const credential = verificationResult.data.credential;
831
855
  const delegationUserIdentifier = credential?.user_identifier;
832
- // Also check for user_id field (AgentShield may return DID or ID directly)
856
+ // Also check for user_id field (Checkpoint may return DID or ID directly)
833
857
  const delegationUserId = credential?.user_id;
834
858
  const sessionUserDid = session?.userDid;
835
859
 
@@ -840,8 +864,8 @@ export class MCPIRuntimeBase {
840
864
  delegationUserId === sessionUserDid;
841
865
 
842
866
  // Special case: If delegationUserIdentifier is NOT a DID (e.g., email),
843
- // but AgentShield verified the delegation, trust it.
844
- // AgentShield internally links email → DID, so the verification is valid.
867
+ // but Checkpoint verified the delegation, trust it.
868
+ // Checkpoint internally links email → DID, so the verification is valid.
845
869
  // Only fail if BOTH are DIDs and they don't match.
846
870
  const isDelegationIdentifierDid =
847
871
  delegationUserIdentifier.startsWith("did:");
@@ -903,7 +927,7 @@ export class MCPIRuntimeBase {
903
927
  );
904
928
  }
905
929
 
906
- // User identifier validation passed (direct match or trusted AgentShield verification)
930
+ // User identifier validation passed (direct match or trusted Checkpoint verification)
907
931
  if (this.config.environment === "development") {
908
932
  console.error("[MCP-I] ✅ User identifier validation PASSED", {
909
933
  tool: toolName,
@@ -912,7 +936,7 @@ export class MCPIRuntimeBase {
912
936
  sessionId: session?.id?.substring(0, 20) + "...",
913
937
  matchType: identifiersMatch
914
938
  ? "direct"
915
- : "trusted_agentshield_verification",
939
+ : "trusted_checkpoint_verification",
916
940
  delegationIdentifierFormat: isDelegationIdentifierDid
917
941
  ? "did"
918
942
  : "email_or_other",
@@ -936,7 +960,7 @@ export class MCPIRuntimeBase {
936
960
 
937
961
  // ✅ SECURITY: Validate authorization method matches tool requirements
938
962
  // This prevents stale delegations from working after tool auth method changes
939
- // NOTE: Authorization validation only applies when credential is present (AgentShield API verifier).
963
+ // NOTE: Authorization validation only applies when credential is present (Checkpoint API verifier).
940
964
  // KV/Memory verifiers don't return credential data, so we skip auth method validation for them.
941
965
  const toolAuth = protection.authorization;
942
966
  const delegationAuth = credential?.authorization as
@@ -945,7 +969,7 @@ export class MCPIRuntimeBase {
945
969
 
946
970
  // Only validate when:
947
971
  // 1. Tool has authorization requirement defined
948
- // 2. Credential is present (AgentShield API verifier)
972
+ // 2. Credential is present (Checkpoint API verifier)
949
973
  if (toolAuth && credential) {
950
974
  // If tool requires authorization but credential doesn't have auth data, reject
951
975
  // This prevents bypassing auth checks with incomplete credential data
@@ -1067,6 +1091,10 @@ export class MCPIRuntimeBase {
1067
1091
  }
1068
1092
  // If credential is missing entirely (KV/Memory verifiers), skip validation for backward compatibility
1069
1093
 
1094
+ // Every check passed: hand the verifier's answer to the handler so
1095
+ // it can enforce grant constraints from what was verified just now.
1096
+ verifiedDelegation = toVerifiedDelegation(verificationResult.data);
1097
+
1070
1098
  // Verification succeeded
1071
1099
  if (this.config.environment === "development") {
1072
1100
  console.error("[MCP-I] ✅ Delegation verification SUCCEEDED", {
@@ -1084,8 +1112,8 @@ export class MCPIRuntimeBase {
1084
1112
  throw error;
1085
1113
  }
1086
1114
 
1087
- // Handle AgentShieldAPIError (network errors, API errors, etc.)
1088
- if (error instanceof AgentShieldAPIError) {
1115
+ // Handle CheckpointAPIError (network errors, API errors, etc.)
1116
+ if (error instanceof CheckpointAPIError) {
1089
1117
  if (this.config.environment === "development") {
1090
1118
  console.error(
1091
1119
  "[MCP-I] ❌ Delegation verification error (API failure)",
@@ -1191,8 +1219,11 @@ export class MCPIRuntimeBase {
1191
1219
  }
1192
1220
  }
1193
1221
 
1194
- // Execute the tool
1195
- const result = await handler(args);
1222
+ // Execute the tool. One-argument call when nothing was verified, so
1223
+ // handlers that inspect their arity or `arguments` see today's call.
1224
+ const result = verifiedDelegation
1225
+ ? await handler(args, verifiedDelegation)
1226
+ : await handler(args);
1196
1227
 
1197
1228
  // Create proof
1198
1229
  const proof = await this.createProof(result, session);
@@ -1223,7 +1254,7 @@ export class MCPIRuntimeBase {
1223
1254
  */
1224
1255
  async resumeToolCall(
1225
1256
  resumeToken: string,
1226
- handler: (args: unknown) => Promise<unknown>,
1257
+ handler: (args: unknown, verified?: VerifiedDelegation) => Promise<unknown>,
1227
1258
  delegationToken?: string
1228
1259
  ): Promise<unknown> {
1229
1260
  const interceptedCall = this.interceptedCalls.get(resumeToken);
@@ -1292,12 +1323,12 @@ export class MCPIRuntimeBase {
1292
1323
  }
1293
1324
 
1294
1325
  /**
1295
- * Build consent URL for AgentShield delegation flow
1326
+ * Build consent URL for Checkpoint delegation flow
1296
1327
  *
1297
- * Note: Parameter names use snake_case for AgentShield API compatibility.
1328
+ * Note: Parameter names use snake_case for Checkpoint API compatibility.
1298
1329
  * This is documented in docs/API_PARITY_GUIDE.md under "Field Naming Conventions".
1299
1330
  *
1300
- * AgentShield API requires snake_case in URL parameters:
1331
+ * Checkpoint API requires snake_case in URL parameters:
1301
1332
  * - session_id (not sessionId)
1302
1333
  * - agent_did (not agentDid)
1303
1334
  * - resume_token (not resumeToken)
@@ -1307,7 +1338,7 @@ export class MCPIRuntimeBase {
1307
1338
  * @param scopes - Required scopes for the tool
1308
1339
  * @param session - Current session context
1309
1340
  * @param resumeToken - Token to resume after delegation
1310
- * @param projectId - Project ID for AgentShield API
1341
+ * @param projectId - Project ID for Checkpoint API
1311
1342
  * @param provider - Provider name (e.g., "github", "credentials") to select specific auth method
1312
1343
  * @returns Full consent URL with snake_case parameters
1313
1344
  */
@@ -1391,7 +1422,7 @@ export class MCPIRuntimeBase {
1391
1422
  * @param scopes - Required scopes
1392
1423
  * @param session - Current session context
1393
1424
  * @param resumeToken - Token to resume after delegation
1394
- * @param projectId - AgentShield project ID
1425
+ * @param projectId - Checkpoint project ID
1395
1426
  * @param serverUrl - Server URL for consent approval POST
1396
1427
  * @param clientCapabilities - MCP client capabilities from the session
1397
1428
  */
@@ -1462,8 +1493,8 @@ export class MCPIRuntimeBase {
1462
1493
  provider?: string
1463
1494
  ): string {
1464
1495
  // Default implementation - override in subclasses
1465
- // This URL should point to AgentShield's consent page
1466
- // Parameter names use snake_case for AgentShield API compatibility
1496
+ // This URL should point to Checkpoint's consent page
1497
+ // Parameter names use snake_case for Checkpoint API compatibility
1467
1498
  const params = new URLSearchParams({
1468
1499
  tool: toolName,
1469
1500
  scopes: scopes.join(","),
@@ -1471,14 +1502,14 @@ export class MCPIRuntimeBase {
1471
1502
  agent_did: session?.agentDid || "",
1472
1503
  });
1473
1504
 
1474
- // Add agent_name for AgentShield dashboard display
1505
+ // Add agent_name for Checkpoint dashboard display
1475
1506
  // Priority: session.agentName > "Unknown Agent"
1476
1507
  const agentName = session?.agentName;
1477
1508
  if (agentName) {
1478
1509
  params.set("agent_name", agentName);
1479
1510
  }
1480
1511
 
1481
- // Add project_id if provided (required for AgentShield consent endpoint)
1512
+ // Add project_id if provided (required for Checkpoint consent endpoint)
1482
1513
  if (projectId) {
1483
1514
  params.set("project_id", projectId);
1484
1515
  }
@@ -1494,7 +1525,7 @@ export class MCPIRuntimeBase {
1494
1525
  params.set("provider", provider);
1495
1526
  }
1496
1527
 
1497
- // Use AgentShield consent endpoint
1528
+ // Use Checkpoint consent endpoint
1498
1529
  return `https://kya.vouched.id/bouncer/consent?${params.toString()}`;
1499
1530
  }
1500
1531
 
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Delegation denial mapping
3
+ *
4
+ * When the verifier refuses a presented delegation, clients and the audit
5
+ * ledger need to know why (a revoked grant must not look like a missing one).
6
+ * Upstream codes pass through a fixed allowlist onto DelegationDenialCode.
7
+ * The upstream `message` and `details` are never read: `details.reason` can
8
+ * hold free text an admin typed when revoking.
9
+ *
10
+ * @module @kya-os/mcp-i-runtime/runtime/delegation-denial
11
+ */
12
+
13
+ import type { DelegationDenialCode } from "@kya-os/contracts/config";
14
+
15
+ export type { DelegationDenialCode };
16
+
17
+ /** A verifier refusal, safe to show to clients and to record in audit. */
18
+ export interface DelegationDenial {
19
+ code: DelegationDenialCode;
20
+ /** Always DEFAULT_DENIAL_MESSAGES[code]; never upstream text. */
21
+ message: string;
22
+ }
23
+
24
+ /**
25
+ * Product-neutral default text per denial code. Each one ends with
26
+ * "Nothing was executed." so a client can tell the user the tool had no effect.
27
+ */
28
+ export const DEFAULT_DENIAL_MESSAGES: Readonly<
29
+ Record<DelegationDenialCode, string>
30
+ > = Object.freeze({
31
+ delegation_revoked:
32
+ "This authorization was revoked. Nothing was executed.",
33
+ delegation_expired:
34
+ "This authorization has expired. Nothing was executed.",
35
+ delegation_not_yet_valid:
36
+ "This authorization is not active yet. Nothing was executed.",
37
+ delegation_invalid:
38
+ "This authorization is no longer valid. Nothing was executed.",
39
+ agent_mismatch:
40
+ "This authorization was issued to a different agent. Nothing was executed.",
41
+ user_mismatch:
42
+ "This authorization belongs to a different user. Nothing was executed.",
43
+ native_binding_mismatch:
44
+ "This authorization does not match the agent key presented with this request. Nothing was executed.",
45
+ budget_exceeded:
46
+ "This authorization has used all of its allowed calls. Nothing was executed.",
47
+ insufficient_scope:
48
+ "This authorization does not cover this action. Nothing was executed.",
49
+ policy_denied:
50
+ "This request is outside the access policy of this authorization. Nothing was executed.",
51
+ });
52
+
53
+ // Upstream verifier `error.code` to denial code. A Map, not an object
54
+ // literal, so inherited keys such as "constructor" can never match.
55
+ // Codes left out (billing, limit_exceeded, revocation_check_failed,
56
+ // project_not_found, anything new) map to undefined: the client then sees
57
+ // today's message, because those are not a statement about this grant.
58
+ const UPSTREAM_DENIAL_CODES: ReadonlyMap<string, DelegationDenialCode> =
59
+ new Map<string, DelegationDenialCode>([
60
+ ["delegation_revoked", "delegation_revoked"],
61
+ ["delegation_expired", "delegation_expired"],
62
+ ["delegation_not_yet_valid", "delegation_not_yet_valid"],
63
+ ["delegation_inactive", "delegation_invalid"],
64
+ ["delegation_not_found", "delegation_invalid"],
65
+ ["invalid_token", "delegation_invalid"],
66
+ ["invalid_jwt", "delegation_invalid"],
67
+ ["agent_mismatch", "agent_mismatch"],
68
+ ["user_mismatch", "user_mismatch"],
69
+ ["max_calls_exceeded", "budget_exceeded"],
70
+ ["insufficient_scopes", "insufficient_scope"],
71
+ ["origin_not_allowed", "policy_denied"],
72
+ ["origin_required", "policy_denied"],
73
+ ["ip_not_whitelisted", "policy_denied"],
74
+ ["client_ip_required", "policy_denied"],
75
+ ]);
76
+
77
+ function denialFor(code: DelegationDenialCode): DelegationDenial {
78
+ return { code, message: DEFAULT_DENIAL_MESSAGES[code] };
79
+ }
80
+
81
+ /**
82
+ * Map an upstream verifier code to a denial, or undefined when the code is
83
+ * not on the allowlist.
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * toDelegationDenial("delegation_revoked");
88
+ * // { code: "delegation_revoked", message: "This authorization was revoked. Nothing was executed." }
89
+ * toDelegationDenial("project_not_found"); // undefined
90
+ * ```
91
+ */
92
+ export function toDelegationDenial(
93
+ upstreamCode?: string
94
+ ): DelegationDenial | undefined {
95
+ if (upstreamCode === undefined) return undefined;
96
+ const code = UPSTREAM_DENIAL_CODES.get(upstreamCode);
97
+ return code === undefined ? undefined : denialFor(code);
98
+ }
99
+
100
+ /**
101
+ * The denial for the runtime's own check that a verified grant matches the
102
+ * holder-of-key admitted on this request (native rail only). No upstream code
103
+ * maps here, because only the runtime makes that comparison.
104
+ */
105
+ export function nativeBindingDenial(): DelegationDenial {
106
+ return denialFor("native_binding_mismatch");
107
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Verified delegation mapping
3
+ *
4
+ * Turns the verifier's answer for THIS tool call into the VerifiedDelegation
5
+ * that protected handlers receive. Handlers enforce grant limits from this
6
+ * value, so it is built only from a successful verify response and never from
7
+ * the stored token, tool arguments or session state.
8
+ *
9
+ * @module @kya-os/mcp-i-runtime/runtime/verified-delegation
10
+ */
11
+
12
+ import type { VerifiedDelegation } from "@kya-os/contracts/config";
13
+ import type { VerifyDelegationResponse } from "@kya-os/contracts/checkpoint-api";
14
+
15
+ /**
16
+ * Build a VerifiedDelegation from a verify response.
17
+ *
18
+ * Returns undefined when the verifier did not accept the delegation, or when
19
+ * it returned no credential (KV and memory verifiers), because there is then
20
+ * nothing verified to hand to the handler.
21
+ *
22
+ * The result is a deep copy: a handler that mutates it cannot change the
23
+ * verify response the runtime still holds.
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const verified = toVerifiedDelegation(verificationResult.data);
28
+ * // verified?.constraints?.crisp is what Checkpoint echoed for this call
29
+ * ```
30
+ */
31
+ export function toVerifiedDelegation(
32
+ data: VerifyDelegationResponse
33
+ ): VerifiedDelegation | undefined {
34
+ if (data.valid !== true) return undefined;
35
+
36
+ const credential = data.credential;
37
+ if (!credential) return undefined;
38
+
39
+ const constraints = credential.constraints
40
+ ? structuredClone(credential.constraints)
41
+ : undefined;
42
+ const expiresAt = positiveSeconds(constraints?.not_after);
43
+
44
+ return {
45
+ ...(data.delegation_id === undefined ? {} : { id: data.delegation_id }),
46
+ ...(credential.agent_did === undefined
47
+ ? {}
48
+ : { agentDid: credential.agent_did }),
49
+ ...(credential.user_did === undefined
50
+ ? {}
51
+ : { userDid: credential.user_did }),
52
+ // Only a real array of scopes is authority; anything else means none.
53
+ scopes: Array.isArray(credential.scopes) ? [...credential.scopes] : [],
54
+ ...(constraints === undefined ? {} : { constraints }),
55
+ ...(credential.authorization?.type === undefined
56
+ ? {}
57
+ : { authorizationType: credential.authorization.type }),
58
+ ...(expiresAt === undefined ? {} : { expiresAt }),
59
+ };
60
+ }
61
+
62
+ // Checkpoint stores `not_after: 0` for "no expiry", so only a positive number
63
+ // is a real deadline.
64
+ function positiveSeconds(value: unknown): number | undefined {
65
+ return typeof value === "number" && value > 0 ? value : undefined;
66
+ }
@@ -18,8 +18,8 @@ import {
18
18
  } from "../../__tests__/utils/mock-providers.js";
19
19
  import type { ProviderRuntimeConfig } from "../../config.js";
20
20
  import type { DetachedProof } from "@kya-os/contracts/proof";
21
- import type { VerifyDelegationRequest, ProofSubmissionRequest } from "@kya-os/contracts/agentshield-api";
22
- import { AgentShieldAPIError } from "@kya-os/contracts/agentshield-api";
21
+ import type { VerifyDelegationRequest, ProofSubmissionRequest } from "@kya-os/contracts/checkpoint-api";
22
+ import { CheckpointAPIError } from "@kya-os/contracts/checkpoint-api";
23
23
 
24
24
  describe("AccessControlApiService Integration", () => {
25
25
  let accessControlService: AccessControlApiService;
@@ -432,7 +432,7 @@ describe("AccessControlApiService Integration", () => {
432
432
 
433
433
  await expect(
434
434
  accessControlService.verifyDelegation(request)
435
- ).rejects.toThrow(AgentShieldAPIError);
435
+ ).rejects.toThrow(CheckpointAPIError);
436
436
 
437
437
  // Should not retry
438
438
  expect(mockFetchProvider.fetch).toHaveBeenCalledTimes(1);
@@ -4,13 +4,13 @@
4
4
  * These tests verify that the proof submission response format matches
5
5
  * the schema defined in @kya-os/contracts, preventing regressions.
6
6
  *
7
- * CRITICAL: These tests ensure API parity between MCP-I and AgentShield/Bouncer.
7
+ * CRITICAL: These tests ensure API parity between MCP-I and Checkpoint/Bouncer.
8
8
  */
9
9
 
10
10
  import { describe, it, expect, vi, beforeEach } from "vitest";
11
11
  import { AccessControlApiService } from "../access-control.service";
12
- import { proofSubmissionResponseSchema } from "@kya-os/contracts/agentshield-api";
13
- import type { ProofSubmissionRequest } from "@kya-os/contracts/agentshield-api";
12
+ import { proofSubmissionResponseSchema } from "@kya-os/contracts/checkpoint-api";
13
+ import type { ProofSubmissionRequest } from "@kya-os/contracts/checkpoint-api";
14
14
 
15
15
  describe("Proof Submission Response Validation", () => {
16
16
  let service: AccessControlApiService;
@@ -28,7 +28,7 @@ describe("Proof Submission Response Validation", () => {
28
28
  });
29
29
  });
30
30
 
31
- describe("Wrapped Response Format (AgentShield API)", () => {
31
+ describe("Wrapped Response Format (Checkpoint API)", () => {
32
32
  it("should validate wrapped response with success field in data", async () => {
33
33
  const request: ProofSubmissionRequest = {
34
34
  session_id: "test-session",
@@ -50,7 +50,7 @@ describe("Proof Submission Response Validation", () => {
50
50
  ],
51
51
  };
52
52
 
53
- // Simulate AgentShield API wrapped response
53
+ // Simulate Checkpoint API wrapped response
54
54
  const wrappedResponse = {
55
55
  success: true,
56
56
  data: {
@@ -272,9 +272,9 @@ describe("Proof Submission Response Validation", () => {
272
272
  expect(result.success).toBe(true);
273
273
  });
274
274
 
275
- it("should validate schema directly matches AgentShield response format", () => {
276
- // This test ensures the schema matches what AgentShield actually returns
277
- const agentShieldResponseData = {
275
+ it("should validate schema directly matches Checkpoint response format", () => {
276
+ // This test ensures the schema matches what Checkpoint actually returns
277
+ const checkpointResponseData = {
278
278
  success: true,
279
279
  accepted: 1,
280
280
  rejected: 0,
@@ -287,16 +287,16 @@ describe("Proof Submission Response Validation", () => {
287
287
  };
288
288
 
289
289
  const validation = proofSubmissionResponseSchema.safeParse(
290
- agentShieldResponseData
290
+ checkpointResponseData
291
291
  );
292
292
  expect(validation.success).toBe(true);
293
293
  if (validation.success) {
294
- expect(validation.data).toMatchObject(agentShieldResponseData);
294
+ expect(validation.data).toMatchObject(checkpointResponseData);
295
295
  }
296
296
  });
297
297
 
298
- it("should validate schema with errors array matches AgentShield format", () => {
299
- const agentShieldResponseData = {
298
+ it("should validate schema with errors array matches Checkpoint format", () => {
299
+ const checkpointResponseData = {
300
300
  success: true,
301
301
  accepted: 0,
302
302
  rejected: 1,
@@ -319,7 +319,7 @@ describe("Proof Submission Response Validation", () => {
319
319
  };
320
320
 
321
321
  const validation = proofSubmissionResponseSchema.safeParse(
322
- agentShieldResponseData
322
+ checkpointResponseData
323
323
  );
324
324
  expect(validation.success).toBe(true);
325
325
  if (validation.success) {
@@ -332,7 +332,7 @@ describe("Proof Submission Response Validation", () => {
332
332
 
333
333
  describe("Regression Prevention", () => {
334
334
  it("should prevent regression: missing success field in data", () => {
335
- // This test ensures we catch if AgentShield changes response format
335
+ // This test ensures we catch if Checkpoint changes response format
336
336
  const responseWithoutSuccess = {
337
337
  accepted: 1,
338
338
  rejected: 0,
@@ -419,7 +419,7 @@ describe("Proof Submission Response Validation", () => {
419
419
  ],
420
420
  };
421
421
 
422
- // Simulate the exact response format from AgentShield API
422
+ // Simulate the exact response format from Checkpoint API
423
423
  // This matches the format seen in production logs
424
424
  const wrappedResponse = {
425
425
  success: true,