@kya-os/mcp-i-runtime 1.3.1 → 1.3.3

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 (122) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/handshake.d.ts +23 -43
  3. package/dist/auth/handshake.d.ts.map +1 -1
  4. package/dist/auth/handshake.js +51 -82
  5. package/dist/auth/handshake.js.map +1 -1
  6. package/dist/auth/index.d.ts +1 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js.map +1 -1
  9. package/dist/auth/resume-token.d.ts +52 -0
  10. package/dist/auth/resume-token.d.ts.map +1 -0
  11. package/dist/auth/resume-token.js +89 -0
  12. package/dist/auth/resume-token.js.map +1 -0
  13. package/dist/auth/types.d.ts +15 -0
  14. package/dist/auth/types.d.ts.map +1 -1
  15. package/dist/index.d.ts +7 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +25 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/proof/companion.d.ts +25 -0
  20. package/dist/proof/companion.d.ts.map +1 -0
  21. package/dist/proof/companion.js +14 -0
  22. package/dist/proof/companion.js.map +1 -0
  23. package/dist/proof/generator.d.ts +22 -9
  24. package/dist/proof/generator.d.ts.map +1 -1
  25. package/dist/proof/generator.js +20 -27
  26. package/dist/proof/generator.js.map +1 -1
  27. package/dist/proof/index.d.ts +2 -1
  28. package/dist/proof/index.d.ts.map +1 -1
  29. package/dist/proof/index.js +3 -1
  30. package/dist/proof/index.js.map +1 -1
  31. package/dist/runtime/audit.d.ts.map +1 -1
  32. package/dist/runtime/audit.js +78 -18
  33. package/dist/runtime/audit.js.map +1 -1
  34. package/dist/runtime/base.d.ts +6 -1
  35. package/dist/runtime/base.d.ts.map +1 -1
  36. package/dist/runtime/base.js +65 -17
  37. package/dist/runtime/base.js.map +1 -1
  38. package/dist/runtime/dif-core.d.ts +8 -0
  39. package/dist/runtime/dif-core.d.ts.map +1 -1
  40. package/dist/runtime/dif-core.js +10 -0
  41. package/dist/runtime/dif-core.js.map +1 -1
  42. package/dist/services/access-control.service.d.ts.map +1 -1
  43. package/dist/services/access-control.service.js +12 -5
  44. package/dist/services/access-control.service.js.map +1 -1
  45. package/dist/services/claims-first-guard.d.ts +33 -0
  46. package/dist/services/claims-first-guard.d.ts.map +1 -0
  47. package/dist/services/claims-first-guard.js +77 -0
  48. package/dist/services/claims-first-guard.js.map +1 -0
  49. package/dist/services/holder-keys.d.ts +95 -0
  50. package/dist/services/holder-keys.d.ts.map +1 -0
  51. package/dist/services/holder-keys.js +281 -0
  52. package/dist/services/holder-keys.js.map +1 -0
  53. package/dist/services/holder-read-slots.d.ts +42 -0
  54. package/dist/services/holder-read-slots.d.ts.map +1 -0
  55. package/dist/services/holder-read-slots.js +82 -0
  56. package/dist/services/holder-read-slots.js.map +1 -0
  57. package/dist/services/proof-verifier.d.ts +13 -35
  58. package/dist/services/proof-verifier.d.ts.map +1 -1
  59. package/dist/services/proof-verifier.js +16 -74
  60. package/dist/services/proof-verifier.js.map +1 -1
  61. package/dist/services/request-holder.d.ts +78 -0
  62. package/dist/services/request-holder.d.ts.map +1 -0
  63. package/dist/services/request-holder.js +81 -0
  64. package/dist/services/request-holder.js.map +1 -0
  65. package/dist/services/tool-context-builder.d.ts.map +1 -1
  66. package/dist/services/tool-context-builder.js +16 -4
  67. package/dist/services/tool-context-builder.js.map +1 -1
  68. package/dist/services/tool-protection.service.d.ts +7 -0
  69. package/dist/services/tool-protection.service.d.ts.map +1 -1
  70. package/dist/services/tool-protection.service.js +34 -15
  71. package/dist/services/tool-protection.service.js.map +1 -1
  72. package/dist/types/tool-protection.d.ts +94 -0
  73. package/dist/types/tool-protection.d.ts.map +1 -1
  74. package/dist/types/tool-protection.js +113 -1
  75. package/dist/types/tool-protection.js.map +1 -1
  76. package/eslint.config.js +20 -0
  77. package/package.json +8 -2
  78. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  79. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  80. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  81. package/src/__tests__/runtime/audit.test.ts +363 -53
  82. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  83. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  84. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  85. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  86. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  87. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  88. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  89. package/src/auth/__tests__/verify-or-hints-presented.test.ts +155 -0
  90. package/src/auth/handshake.ts +80 -125
  91. package/src/auth/index.ts +1 -0
  92. package/src/auth/resume-token.ts +134 -0
  93. package/src/auth/types.ts +20 -2
  94. package/src/index.ts +40 -1
  95. package/src/proof/__tests__/proof-generator.test.ts +80 -13
  96. package/src/proof/companion.ts +35 -0
  97. package/src/proof/generator.ts +51 -33
  98. package/src/proof/index.ts +3 -0
  99. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  100. package/src/runtime/audit.ts +170 -65
  101. package/src/runtime/base.ts +95 -31
  102. package/src/runtime/dif-core.ts +16 -0
  103. package/src/services/__tests__/access-control.service.test.ts +44 -0
  104. package/src/services/__tests__/claims-first-guard.test.ts +93 -0
  105. package/src/services/__tests__/holder-fixtures.ts +135 -0
  106. package/src/services/__tests__/holder-keys.test.ts +257 -0
  107. package/src/services/__tests__/holder-read-slots.test.ts +117 -0
  108. package/src/services/__tests__/holder-reads.test.ts +284 -0
  109. package/src/services/__tests__/proof-verifier.test.ts +286 -195
  110. package/src/services/__tests__/request-holder.test.ts +210 -0
  111. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  112. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  113. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  114. package/src/services/access-control.service.ts +11 -5
  115. package/src/services/claims-first-guard.ts +89 -0
  116. package/src/services/holder-keys.ts +379 -0
  117. package/src/services/holder-read-slots.ts +85 -0
  118. package/src/services/proof-verifier.ts +18 -79
  119. package/src/services/request-holder.ts +146 -0
  120. package/src/services/tool-context-builder.ts +19 -4
  121. package/src/services/tool-protection.service.ts +62 -19
  122. package/src/types/tool-protection.ts +161 -0
@@ -15,7 +15,14 @@ import {
15
15
  IdentityProvider,
16
16
  AgentIdentity,
17
17
  } from "../providers/base";
18
- import { DelegationRequiredError } from "../types/tool-protection.js";
18
+ import {
19
+ AmountLimitError,
20
+ DelegationRequiredError,
21
+ isUnavailableToolProtection,
22
+ namesRequiredScope,
23
+ unavailableToolProtectionError,
24
+ unscopedToolProtectionError,
25
+ } from "../types/tool-protection.js";
19
26
  import { CryptoService, type Ed25519JWK } from "../services/crypto.service.js";
20
27
  import { ProofVerifier } from "../services/proof-verifier.js";
21
28
  import type { DetachedProof } from "@kya-os/contracts/proof";
@@ -31,6 +38,7 @@ import type { AccessControlApiService } from "../services/access-control.service
31
38
  import { authorizationMatches } from "../services/access-control.service.js";
32
39
  import type { VerifyDelegationRequest } from "@kya-os/contracts/checkpoint-api";
33
40
  import { CheckpointAPIError } from "@kya-os/contracts/checkpoint-api";
41
+ import { findAmountLimitViolation } from "@kya-os/contracts/delegation";
34
42
  import type { VerifiedDelegation } from "@kya-os/contracts/config";
35
43
  import { toVerifiedDelegation } from "./verified-delegation.js";
36
44
  import {
@@ -525,7 +533,10 @@ export class MCPIRuntimeBase {
525
533
  // A tool failure is the primary error. Do not replace it with a
526
534
  // terminal-delivery error and accidentally make retries ambiguous.
527
535
  console.error("[MCP-I] Failed to record terminal tool audit event", {
528
- error: auditError instanceof Error ? auditError.message : String(auditError),
536
+ error:
537
+ auditError instanceof Error
538
+ ? auditError.message
539
+ : String(auditError),
529
540
  });
530
541
  }
531
542
  }
@@ -535,7 +546,9 @@ export class MCPIRuntimeBase {
535
546
  if (!auditInvocation || !this.config.auditTrail) return result;
536
547
 
537
548
  try {
538
- const terminal = await auditInvocation.terminal(terminalForToolResult(result));
549
+ const terminal = await auditInvocation.terminal(
550
+ terminalForToolResult(result)
551
+ );
539
552
  return attachRuntimeAuditMetadata(
540
553
  result,
541
554
  this.config.auditTrail.sourceId,
@@ -548,7 +561,8 @@ export class MCPIRuntimeBase {
548
561
  // an explicit degraded/error marker; primitives fail closed because they
549
562
  // cannot carry trustworthy delivery metadata.
550
563
  console.error("[MCP-I] Failed to record successful tool audit terminal", {
551
- error: auditError instanceof Error ? auditError.message : String(auditError),
564
+ error:
565
+ auditError instanceof Error ? auditError.message : String(auditError),
552
566
  });
553
567
  return attachRuntimeAuditMetadata(
554
568
  result,
@@ -569,6 +583,7 @@ export class MCPIRuntimeBase {
569
583
  // Set only after every check below passes. Local to this call, so
570
584
  // concurrent calls on the same runtime never see each other's grant.
571
585
  let verifiedDelegation: VerifiedDelegation | undefined;
586
+ let grantConstraints: unknown;
572
587
 
573
588
  // Check tool protection (delegation requirement)
574
589
  if (this.config.toolProtectionService) {
@@ -590,6 +605,18 @@ export class MCPIRuntimeBase {
590
605
  );
591
606
 
592
607
  if (protection) {
608
+ // No config could be read and none is cached: the service's stand-in.
609
+ // Refused until a config arrives.
610
+ if (isUnavailableToolProtection(protection)) {
611
+ throw unavailableToolProtectionError(toolName);
612
+ }
613
+ // A protection that names no scope has nothing to check a delegation
614
+ // against, so it can't be enforced: refused before consent or
615
+ // verification, never passed as satisfied.
616
+ if (!namesRequiredScope(protection.requiredScopes)) {
617
+ throw unscopedToolProtectionError(toolName);
618
+ }
619
+
593
620
  // Tool requires delegation
594
621
  const hasDelegation = session?.delegationToken || session?.consentProof;
595
622
 
@@ -874,19 +901,18 @@ export class MCPIRuntimeBase {
874
901
 
875
902
  if (shouldEnforceMatch && !identifiersMatch) {
876
903
  // User identifier mismatch - potential security issue
877
- const securityError = `Delegation user_identifier mismatch: delegation has "${delegationUserIdentifier.substring(0, 20)}..." but session has "${sessionUserDid.substring(0, 20)}..."`;
878
-
879
904
  if (this.config.environment === "development") {
880
905
  console.error(
881
906
  "[MCP-I] 🔒 SECURITY: User identifier validation FAILED",
882
907
  {
883
908
  tool: toolName,
884
909
  agentDid: identity.did.slice(0, 20) + "...",
885
- delegationUserIdentifier:
886
- delegationUserIdentifier.substring(0, 20) + "...",
887
- delegationUserId: delegationUserId
888
- ? delegationUserId.substring(0, 20) + "..."
889
- : "N/A",
910
+ // The identifier can be an email and the id a
911
+ // customer number: log their shape, never the values.
912
+ delegationIdentifierFormat: isDelegationIdentifierDid
913
+ ? "did"
914
+ : "email_or_other",
915
+ hasDelegationUserId: !!delegationUserId,
890
916
  sessionUserDid: sessionUserDid.substring(0, 20) + "...",
891
917
  sessionId: session?.id?.substring(0, 20) + "...",
892
918
  reason: "user_identifier_mismatch",
@@ -950,8 +976,10 @@ export class MCPIRuntimeBase {
950
976
  {
951
977
  tool: toolName,
952
978
  agentDid: identity.did.slice(0, 20) + "...",
953
- delegationUserIdentifier:
954
- delegationUserIdentifier.substring(0, 20) + "...",
979
+ delegationIdentifierFormat:
980
+ delegationUserIdentifier.startsWith("did:")
981
+ ? "did"
982
+ : "email_or_other",
955
983
  sessionId: session?.id?.substring(0, 20) + "...",
956
984
  }
957
985
  );
@@ -1094,6 +1122,9 @@ export class MCPIRuntimeBase {
1094
1122
  // Every check passed: hand the verifier's answer to the handler so
1095
1123
  // it can enforce grant constraints from what was verified just now.
1096
1124
  verifiedDelegation = toVerifiedDelegation(verificationResult.data);
1125
+ grantConstraints =
1126
+ verifiedDelegation?.constraints ??
1127
+ verificationResult.data.delegation?.constraints;
1097
1128
 
1098
1129
  // Verification succeeded
1099
1130
  if (this.config.environment === "development") {
@@ -1204,6 +1235,18 @@ export class MCPIRuntimeBase {
1204
1235
  );
1205
1236
  }
1206
1237
  }
1238
+
1239
+ if (protection.amount) {
1240
+ const amountViolation = findAmountLimitViolation({
1241
+ args,
1242
+ amountConfig: protection.amount,
1243
+ requiredScopes: protection.requiredScopes,
1244
+ constraints: grantConstraints,
1245
+ });
1246
+ if (amountViolation) {
1247
+ throw new AmountLimitError(toolName, amountViolation);
1248
+ }
1249
+ }
1207
1250
  } else {
1208
1251
  // No protection required - tool can be executed freely
1209
1252
  if (this.config.environment === "development") {
@@ -1457,7 +1500,11 @@ export class MCPIRuntimeBase {
1457
1500
  content: [
1458
1501
  {
1459
1502
  type: "text",
1460
- text: `Authorization required for tool "${toolName}". Please approve in the consent form below, or open this link to authorize in your browser: ${consentUrl}`,
1503
+ text: `Authorization required for tool "${toolName}". Please approve in the consent form below.${
1504
+ consentUrl
1505
+ ? ` Or open this link to authorize in your browser: ${consentUrl}`
1506
+ : ""
1507
+ }`,
1461
1508
  },
1462
1509
  ],
1463
1510
  structuredContent: {
@@ -1471,7 +1518,7 @@ export class MCPIRuntimeBase {
1471
1518
  projectId: projectId || "",
1472
1519
  resumeToken: resumeToken || "",
1473
1520
  serverUrl: serverUrl || "",
1474
- consentUrl,
1521
+ ...(consentUrl ? { consentUrl } : {}),
1475
1522
  ...(provider ? { provider } : {}),
1476
1523
  },
1477
1524
  _meta: {
@@ -1484,6 +1531,11 @@ export class MCPIRuntimeBase {
1484
1531
  };
1485
1532
  }
1486
1533
 
1534
+ /**
1535
+ * The configured authorization URL with this request's parameters, or
1536
+ * undefined when none is configured. Runtimes that serve their own consent
1537
+ * page override this.
1538
+ */
1487
1539
  protected buildConsentUrl(
1488
1540
  toolName: string,
1489
1541
  scopes: string[],
@@ -1491,10 +1543,16 @@ export class MCPIRuntimeBase {
1491
1543
  resumeToken?: string,
1492
1544
  projectId?: string,
1493
1545
  provider?: string
1494
- ): string {
1495
- // Default implementation - override in subclasses
1496
- // This URL should point to Checkpoint's consent page
1497
- // Parameter names use snake_case for Checkpoint API compatibility
1546
+ ): string | undefined {
1547
+ const configured = this.config.delegation?.authorization?.authorizationUrl;
1548
+ if (!configured) return undefined;
1549
+ let url: URL;
1550
+ try {
1551
+ url = new URL(configured);
1552
+ } catch {
1553
+ return undefined;
1554
+ }
1555
+
1498
1556
  const params = new URLSearchParams({
1499
1557
  tool: toolName,
1500
1558
  scopes: scopes.join(","),
@@ -1502,14 +1560,14 @@ export class MCPIRuntimeBase {
1502
1560
  agent_did: session?.agentDid || "",
1503
1561
  });
1504
1562
 
1505
- // Add agent_name for Checkpoint dashboard display
1563
+ // Add agent_name for display
1506
1564
  // Priority: session.agentName > "Unknown Agent"
1507
1565
  const agentName = session?.agentName;
1508
1566
  if (agentName) {
1509
1567
  params.set("agent_name", agentName);
1510
1568
  }
1511
1569
 
1512
- // Add project_id if provided (required for Checkpoint consent endpoint)
1570
+ // Add project_id if provided
1513
1571
  if (projectId) {
1514
1572
  params.set("project_id", projectId);
1515
1573
  }
@@ -1525,8 +1583,10 @@ export class MCPIRuntimeBase {
1525
1583
  params.set("provider", provider);
1526
1584
  }
1527
1585
 
1528
- // Use Checkpoint consent endpoint
1529
- return `https://kya.vouched.id/bouncer/consent?${params.toString()}`;
1586
+ for (const [key, value] of params) {
1587
+ url.searchParams.set(key, value);
1588
+ }
1589
+ return url.toString();
1530
1590
  }
1531
1591
 
1532
1592
  /**
@@ -1643,9 +1703,10 @@ export class MCPIRuntimeBase {
1643
1703
 
1644
1704
  if (result.valid && session) {
1645
1705
  // Store canonical payload in session for detached JWS consumers
1646
- const canonicalPayload = this.proofVerifier.buildCanonicalPayload(
1647
- detachedProof.meta
1648
- );
1706
+ const canonicalPayload =
1707
+ await this.proofVerifier.buildCanonicalPayload(
1708
+ detachedProof.meta
1709
+ );
1649
1710
  session.canonicalPayload = canonicalPayload;
1650
1711
  }
1651
1712
 
@@ -2097,11 +2158,14 @@ export class MCPIRuntimeBase {
2097
2158
  /** Development-only diagnostics. These records make no audit assurance claim. */
2098
2159
  private emitDiagnostic(event: string, data: unknown): void {
2099
2160
  if (this.config.environment !== "development") return;
2100
- console.error("[MCP-I diagnostic]", JSON.stringify({
2101
- event,
2102
- data,
2103
- timestamp: this.clock.now(),
2104
- }));
2161
+ console.error(
2162
+ "[MCP-I diagnostic]",
2163
+ JSON.stringify({
2164
+ event,
2165
+ data,
2166
+ timestamp: this.clock.now(),
2167
+ })
2168
+ );
2105
2169
  }
2106
2170
 
2107
2171
  private createDIDDocument(identity: AgentIdentity): DIDDocument {
@@ -37,3 +37,19 @@ let cached: Promise<DifCore> | undefined;
37
37
  export function loadDifCore(): Promise<DifCore> {
38
38
  return (cached ??= import("@kya-os/mcp"));
39
39
  }
40
+
41
+ /** The `@kya-os/mcp/card` module: Entity Card and per-request proofs. */
42
+ export type DifCard = typeof import("@kya-os/mcp/card", {
43
+ with: { "resolution-mode": "import" }
44
+ });
45
+
46
+ let cachedCard: Promise<DifCard> | undefined;
47
+
48
+ /**
49
+ * Resolve `@kya-os/mcp/card` through the same cached dynamic import as
50
+ * {@link loadDifCore}: its request-proof guard (`requireProof`) and nonce
51
+ * cache verify which key a call proves it holds.
52
+ */
53
+ export function loadDifCard(): Promise<DifCard> {
54
+ return (cachedCard ??= import("@kya-os/mcp/card"));
55
+ }
@@ -1046,6 +1046,50 @@ describe("authorizationMatches", () => {
1046
1046
  });
1047
1047
  });
1048
1048
 
1049
+ describe.each([
1050
+ ["oauth", "oauth2"],
1051
+ ["oauth2", "oauth"],
1052
+ ["oauth2", "oauth2"],
1053
+ ])("OAuth aliases (%s delegation, %s requirement)", (delegationType, requiredType) => {
1054
+ it("accepts the same provider across supported OAuth aliases", () => {
1055
+ expect(authorizationMatches(
1056
+ { type: delegationType, provider: "github" },
1057
+ { type: requiredType, provider: "github" }
1058
+ )).toBe(true);
1059
+ });
1060
+
1061
+ it.each(["custom", "google", "GitHub", undefined])(
1062
+ "rejects a delegation provider of %s when GitHub is required",
1063
+ (provider) => {
1064
+ expect(authorizationMatches(
1065
+ { type: delegationType, provider },
1066
+ { type: requiredType, provider: "github" }
1067
+ )).toBe(false);
1068
+ }
1069
+ );
1070
+
1071
+ it("allows any provider only when the tool has no provider requirement", () => {
1072
+ expect(authorizationMatches(
1073
+ { type: delegationType, provider: "github" },
1074
+ { type: requiredType }
1075
+ )).toBe(true);
1076
+ });
1077
+ });
1078
+
1079
+ it.each(["password", "none", "apikey", "verifiable_credential"])(
1080
+ "does not make %s authorization interchangeable with OAuth",
1081
+ (type) => {
1082
+ expect(authorizationMatches(
1083
+ { type, provider: "github" },
1084
+ { type: "oauth2", provider: "github" }
1085
+ )).toBe(false);
1086
+ expect(authorizationMatches(
1087
+ { type: "oauth2", provider: "github" },
1088
+ { type, provider: "github" }
1089
+ )).toBe(false);
1090
+ }
1091
+ );
1092
+
1049
1093
  describe("verifiable_credential type matching", () => {
1050
1094
  it("should return true when credentialTypes match", () => {
1051
1095
  const delegationAuth = { type: "verifiable_credential", credentialType: "api-key" };
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The guard both runtimes verify a request proof with: a holder's key is
3
+ * read only for a proof whose own claims pass.
4
+ */
5
+ import { describe, expect, it, vi } from "vitest";
6
+ import { requireProof } from "@kya-os/mcp/card";
7
+ import { claimsFirstGuard } from "../claims-first-guard";
8
+ import { resolveDidKeyHolder } from "../request-holder";
9
+ import { SERVER, newHolder, signedCall } from "./holder-fixtures";
10
+
11
+ const params = { name: "read", arguments: { id: 1 } };
12
+
13
+ function guarded() {
14
+ const resolveKey = vi.fn(resolveDidKeyHolder);
15
+ const consumeNonceIfFresh = vi.fn(async () => true);
16
+ // The audience is inherited, as a deployment's own dependencies may be.
17
+ const resolveDidKeys = vi.fn(async (did: string) => [
18
+ await resolveDidKeyHolder(`${did}#${did.slice("did:key:".length)}`),
19
+ ]);
20
+ const deps = Object.assign(Object.create({ expectedAudience: SERVER }), {
21
+ resolveKey,
22
+ resolveDidKeys,
23
+ consumeNonceIfFresh,
24
+ });
25
+ return {
26
+ guard: claimsFirstGuard(requireProof, deps),
27
+ resolveKey,
28
+ resolveDidKeys,
29
+ consumeNonceIfFresh,
30
+ };
31
+ }
32
+
33
+ async function proved(audience = SERVER) {
34
+ const holder = newHolder();
35
+ const { method, params: sent } = await signedCall(holder, params, audience);
36
+ const { _meta, ...signed } = sent;
37
+ return { holder, request: { method, params: signed }, meta: _meta };
38
+ }
39
+
40
+ describe("claimsFirstGuard", () => {
41
+ it("verifies a proof its claims pass with its key, and spends its nonce once", async () => {
42
+ const { guard, resolveKey, consumeNonceIfFresh } = guarded();
43
+ const { holder, request, meta } = await proved();
44
+
45
+ expect(await guard(request, meta)).toMatchObject({
46
+ ok: true,
47
+ did: holder.did,
48
+ });
49
+ expect(resolveKey).toHaveBeenCalledTimes(1);
50
+ expect(consumeNonceIfFresh).toHaveBeenCalledTimes(1);
51
+ });
52
+
53
+ it("refuses a proof for another audience with the library's reason, and reads no key", async () => {
54
+ const { guard, resolveKey, resolveDidKeys, consumeNonceIfFresh } =
55
+ guarded();
56
+ const { request, meta } = await proved("did:web:another.example");
57
+
58
+ expect(await guard(request, meta)).toMatchObject({
59
+ ok: false,
60
+ error: { code: "proof_invalid", reasons: ["audience_mismatch"] },
61
+ });
62
+ expect(resolveKey).not.toHaveBeenCalled();
63
+ expect(resolveDidKeys).not.toHaveBeenCalled();
64
+ expect(consumeNonceIfFresh).not.toHaveBeenCalled();
65
+ });
66
+
67
+ it("refuses a proof over other params, and reads no key", async () => {
68
+ const { guard, resolveKey } = guarded();
69
+ const { request, meta } = await proved();
70
+
71
+ const verdict = await guard(
72
+ { ...request, params: { ...request.params, arguments: { id: 2 } } },
73
+ meta
74
+ );
75
+
76
+ expect(verdict).toMatchObject({
77
+ ok: false,
78
+ error: { reasons: ["request_hash_mismatch"] },
79
+ });
80
+ expect(resolveKey).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it("answers a call with no proof as the library does", async () => {
84
+ const { guard, resolveKey } = guarded();
85
+ const { request } = await proved();
86
+
87
+ expect(await guard(request, {})).toMatchObject({
88
+ ok: false,
89
+ error: { code: "proof_missing" },
90
+ });
91
+ expect(resolveKey).not.toHaveBeenCalled();
92
+ });
93
+ });
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Request-holder test fixtures: did:key and did:web holders, the tools/call
3
+ * they sign, and `@kya-os/mcp`'s did:web resolver reading hosted documents.
4
+ */
5
+ import { generateKeyPairSync, randomBytes } from "node:crypto";
6
+ import {
7
+ buildCardProof,
8
+ ed25519SignerFromJwk,
9
+ KYA_OS_CARD_PROOF_META_KEY,
10
+ } from "@kya-os/mcp/card";
11
+ import {
12
+ createDidWebResolver,
13
+ didKeyFragment,
14
+ generateDidKeyFromBytes,
15
+ RuntimeFetchProvider,
16
+ type SafeFetchTransport,
17
+ } from "@kya-os/mcp";
18
+
19
+ export const SERVER = "did:web:server.example";
20
+
21
+ export function newHolder() {
22
+ const { privateKey } = generateKeyPairSync("ed25519");
23
+ const privateJwk = privateKey.export({ format: "jwk" }) as {
24
+ kty: "OKP";
25
+ crv: "Ed25519";
26
+ x: string;
27
+ d: string;
28
+ };
29
+ const did = generateDidKeyFromBytes(
30
+ new Uint8Array(Buffer.from(privateJwk.x, "base64url"))
31
+ );
32
+ return { did, kid: `${did}#${didKeyFragment(did)}`, privateJwk };
33
+ }
34
+
35
+ export type Signer = Pick<
36
+ ReturnType<typeof newHolder>,
37
+ "did" | "kid" | "privateJwk"
38
+ >;
39
+
40
+ export async function signedCall(
41
+ holder: Signer,
42
+ params: Record<string, unknown>,
43
+ audience = SERVER
44
+ ) {
45
+ const minted = await buildCardProof(
46
+ { method: "tools/call", params },
47
+ await ed25519SignerFromJwk(holder),
48
+ { audience, nonce: randomBytes(16).toString("base64url") }
49
+ );
50
+ return {
51
+ method: "tools/call",
52
+ params: {
53
+ ...params,
54
+ _meta: {
55
+ sessionId: "s",
56
+ [KYA_OS_CARD_PROOF_META_KEY]: minted[KYA_OS_CARD_PROOF_META_KEY],
57
+ },
58
+ },
59
+ };
60
+ }
61
+
62
+ /**
63
+ * A did:web holder whose document lists its key as Checkpoint's agent
64
+ * documents do: one Ed25519 key published as a multibase method and as a JWK
65
+ * method, each under `authentication` and `assertionMethod`.
66
+ */
67
+ export function newWebHolder(name: string, host = "agents.example") {
68
+ const { did: keyDid, privateJwk } = newHolder();
69
+ const did = `did:web:${host}:agents:${name}`;
70
+ const methods = [
71
+ {
72
+ id: `${did}#key-1`,
73
+ type: "Ed25519VerificationKey2020",
74
+ controller: did,
75
+ publicKeyMultibase: didKeyFragment(keyDid),
76
+ },
77
+ {
78
+ id: `${did}#key-1-jwk`,
79
+ type: "JsonWebKey2020",
80
+ controller: did,
81
+ publicKeyJwk: { kty: "OKP", crv: "Ed25519", x: privateJwk.x },
82
+ },
83
+ ];
84
+ const document: Record<string, unknown> = {
85
+ "@context": ["https://www.w3.org/ns/did/v1"],
86
+ id: did,
87
+ verificationMethod: methods,
88
+ authentication: methods.map((method) => method.id),
89
+ assertionMethod: methods.map((method) => method.id),
90
+ };
91
+ return { did, kid: `${did}#key-1`, privateJwk, document };
92
+ }
93
+
94
+ /**
95
+ * `@kya-os/mcp`'s did:web resolver over its RuntimeFetchProvider, with the
96
+ * DNS and connection seams answering for every host: a public address, and
97
+ * the documents `hosted` holds by URL (404 for any other). A read answers
98
+ * only once `held` settles, when one is given.
99
+ */
100
+ export function hostedResolver(
101
+ hosted: Map<string, unknown>,
102
+ held?: Promise<void>
103
+ ) {
104
+ const reads: string[] = [];
105
+ const transport: SafeFetchTransport = async (url) => {
106
+ reads.push(url);
107
+ await held;
108
+ const body = hosted.get(url);
109
+ return {
110
+ status: body === undefined ? 404 : 200,
111
+ headers: {
112
+ get: (name: string) =>
113
+ name.toLowerCase() === "content-type" ? "application/json" : null,
114
+ },
115
+ text: async () => (body === undefined ? "" : JSON.stringify(body)),
116
+ };
117
+ };
118
+ const provider = new RuntimeFetchProvider({
119
+ lookup: async () => [{ address: "93.184.216.34", family: 4 }],
120
+ transport,
121
+ });
122
+ return { resolver: createDidWebResolver(provider), reads };
123
+ }
124
+
125
+ export const documentUrl = (name: string, host = "agents.example") =>
126
+ `https://${host}/agents/${name}/did.json`;
127
+
128
+ /** A gate a test opens: `held` settles once `open` is called. */
129
+ export function gate() {
130
+ let open = () => {};
131
+ const held = new Promise<void>((resolve) => {
132
+ open = resolve;
133
+ });
134
+ return { held, open };
135
+ }