@kya-os/mcp-i-cloudflare 1.18.0 → 1.18.2

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 (256) hide show
  1. package/README.md +273 -54
  2. package/dist/adapter.d.ts +3 -17
  3. package/dist/adapter.d.ts.map +1 -1
  4. package/dist/adapter.js +30 -477
  5. package/dist/adapter.js.map +1 -1
  6. package/dist/agent.d.ts +59 -35
  7. package/dist/agent.d.ts.map +1 -1
  8. package/dist/agent.js +383 -406
  9. package/dist/agent.js.map +1 -1
  10. package/dist/app.d.ts.map +1 -1
  11. package/dist/app.js +150 -94
  12. package/dist/app.js.map +1 -1
  13. package/dist/audit/deployment-binding.d.ts +16 -16
  14. package/dist/authority-outcome.d.ts +110 -0
  15. package/dist/authority-outcome.d.ts.map +1 -0
  16. package/dist/authority-outcome.js +154 -0
  17. package/dist/authority-outcome.js.map +1 -0
  18. package/dist/config.d.ts +8 -77
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +0 -83
  21. package/dist/config.js.map +1 -1
  22. package/dist/delegation-http/bearer-retry.d.ts +84 -32
  23. package/dist/delegation-http/bearer-retry.d.ts.map +1 -1
  24. package/dist/delegation-http/bearer-retry.js +124 -139
  25. package/dist/delegation-http/bearer-retry.js.map +1 -1
  26. package/dist/delegation-http/connect-gate.d.ts +47 -0
  27. package/dist/delegation-http/connect-gate.d.ts.map +1 -0
  28. package/dist/delegation-http/connect-gate.js +104 -0
  29. package/dist/delegation-http/connect-gate.js.map +1 -0
  30. package/dist/delegation-http/constants.d.ts +4 -49
  31. package/dist/delegation-http/constants.d.ts.map +1 -1
  32. package/dist/delegation-http/constants.js +4 -58
  33. package/dist/delegation-http/constants.js.map +1 -1
  34. package/dist/delegation-http/issuer-binding.d.ts +26 -0
  35. package/dist/delegation-http/issuer-binding.d.ts.map +1 -0
  36. package/dist/delegation-http/issuer-binding.js +51 -0
  37. package/dist/delegation-http/issuer-binding.js.map +1 -0
  38. package/dist/delegation-http/lazy-auth-gate.d.ts +88 -0
  39. package/dist/delegation-http/lazy-auth-gate.d.ts.map +1 -0
  40. package/dist/delegation-http/lazy-auth-gate.js +203 -0
  41. package/dist/delegation-http/lazy-auth-gate.js.map +1 -0
  42. package/dist/delegation-http/native-challenge.d.ts +52 -0
  43. package/dist/delegation-http/native-challenge.d.ts.map +1 -0
  44. package/dist/delegation-http/native-challenge.js +124 -0
  45. package/dist/delegation-http/native-challenge.js.map +1 -0
  46. package/dist/delegation-http/native-consent-redirect.d.ts +21 -0
  47. package/dist/delegation-http/native-consent-redirect.d.ts.map +1 -0
  48. package/dist/delegation-http/native-consent-redirect.js +43 -0
  49. package/dist/delegation-http/native-consent-redirect.js.map +1 -0
  50. package/dist/delegation-http/native-http.d.ts +1 -86
  51. package/dist/delegation-http/native-http.d.ts.map +1 -1
  52. package/dist/delegation-http/native-http.js +2 -130
  53. package/dist/delegation-http/native-http.js.map +1 -1
  54. package/dist/delegation-http/native-oauth-state-do.d.ts +13 -35
  55. package/dist/delegation-http/native-oauth-state-do.d.ts.map +1 -1
  56. package/dist/delegation-http/native-oauth-state-do.js +10 -165
  57. package/dist/delegation-http/native-oauth-state-do.js.map +1 -1
  58. package/dist/delegation-http/protected-resource.d.ts +37 -0
  59. package/dist/delegation-http/protected-resource.d.ts.map +1 -0
  60. package/dist/delegation-http/protected-resource.js +43 -0
  61. package/dist/delegation-http/protected-resource.js.map +1 -0
  62. package/dist/delegation-http/request-proof.d.ts +20 -0
  63. package/dist/delegation-http/request-proof.d.ts.map +1 -0
  64. package/dist/delegation-http/request-proof.js +29 -0
  65. package/dist/delegation-http/request-proof.js.map +1 -0
  66. package/dist/delegation-http/sid.d.ts +4 -12
  67. package/dist/delegation-http/sid.d.ts.map +1 -1
  68. package/dist/delegation-http/sid.js +4 -19
  69. package/dist/delegation-http/sid.js.map +1 -1
  70. package/dist/delegation-http/well-known-capability.d.ts +8 -12
  71. package/dist/delegation-http/well-known-capability.d.ts.map +1 -1
  72. package/dist/delegation-http/well-known-capability.js +9 -18
  73. package/dist/delegation-http/well-known-capability.js.map +1 -1
  74. package/dist/helpers/env-mapper.d.ts.map +1 -1
  75. package/dist/helpers/env-mapper.js +7 -29
  76. package/dist/helpers/env-mapper.js.map +1 -1
  77. package/dist/index.d.ts +2 -4
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +11 -8
  80. package/dist/index.js.map +1 -1
  81. package/dist/proof-generator.d.ts +24 -17
  82. package/dist/proof-generator.d.ts.map +1 -1
  83. package/dist/proof-generator.js +42 -56
  84. package/dist/proof-generator.js.map +1 -1
  85. package/dist/runtime/oauth-handler.d.ts +1 -1
  86. package/dist/runtime/oauth-handler.d.ts.map +1 -1
  87. package/dist/runtime/oauth-handler.js +15 -30
  88. package/dist/runtime/oauth-handler.js.map +1 -1
  89. package/dist/runtime.d.ts +34 -10
  90. package/dist/runtime.d.ts.map +1 -1
  91. package/dist/runtime.js +54 -12
  92. package/dist/runtime.js.map +1 -1
  93. package/dist/security/admission-refusal.d.ts +3 -3
  94. package/dist/security/admission-refusal.d.ts.map +1 -1
  95. package/dist/security/admission-refusal.js +14 -6
  96. package/dist/security/admission-refusal.js.map +1 -1
  97. package/dist/security/holder-binding.d.ts +34 -0
  98. package/dist/security/holder-binding.d.ts.map +1 -0
  99. package/dist/security/holder-binding.js +75 -0
  100. package/dist/security/holder-binding.js.map +1 -0
  101. package/dist/security/mcp-admission.d.ts +29 -1
  102. package/dist/security/mcp-admission.d.ts.map +1 -1
  103. package/dist/security/mcp-admission.js +78 -12
  104. package/dist/security/mcp-admission.js.map +1 -1
  105. package/dist/security/native-holder-admission.d.ts +39 -0
  106. package/dist/security/native-holder-admission.d.ts.map +1 -0
  107. package/dist/security/native-holder-admission.js +65 -0
  108. package/dist/security/native-holder-admission.js.map +1 -0
  109. package/dist/security/outcome-proof.d.ts +39 -0
  110. package/dist/security/outcome-proof.d.ts.map +1 -0
  111. package/dist/security/outcome-proof.js +54 -0
  112. package/dist/security/outcome-proof.js.map +1 -0
  113. package/dist/security/request-nonce-store.d.ts +43 -0
  114. package/dist/security/request-nonce-store.d.ts.map +1 -0
  115. package/dist/security/request-nonce-store.js +129 -0
  116. package/dist/security/request-nonce-store.js.map +1 -0
  117. package/dist/security/routed-request.d.ts +41 -0
  118. package/dist/security/routed-request.d.ts.map +1 -0
  119. package/dist/security/routed-request.js +86 -0
  120. package/dist/security/routed-request.js.map +1 -0
  121. package/dist/security/sign-in-amr.d.ts +23 -0
  122. package/dist/security/sign-in-amr.d.ts.map +1 -0
  123. package/dist/security/sign-in-amr.js +44 -0
  124. package/dist/security/sign-in-amr.js.map +1 -0
  125. package/dist/services/approval-route.d.ts +3 -2
  126. package/dist/services/approval-route.d.ts.map +1 -1
  127. package/dist/services/approval-route.js.map +1 -1
  128. package/dist/services/checkpoint-decision.d.ts +56 -0
  129. package/dist/services/checkpoint-decision.d.ts.map +1 -0
  130. package/dist/services/checkpoint-decision.js +109 -0
  131. package/dist/services/checkpoint-decision.js.map +1 -0
  132. package/dist/services/consent-page-renderer.d.ts.map +1 -1
  133. package/dist/services/consent-page-renderer.js +2 -3
  134. package/dist/services/consent-page-renderer.js.map +1 -1
  135. package/dist/services/consent.service.d.ts +11 -49
  136. package/dist/services/consent.service.d.ts.map +1 -1
  137. package/dist/services/consent.service.js +81 -307
  138. package/dist/services/consent.service.js.map +1 -1
  139. package/dist/services/credential-auth.handler.d.ts.map +1 -1
  140. package/dist/services/credential-auth.handler.js +2 -8
  141. package/dist/services/credential-auth.handler.js.map +1 -1
  142. package/dist/services/delegation-authority.d.ts +53 -0
  143. package/dist/services/delegation-authority.d.ts.map +1 -0
  144. package/dist/services/delegation-authority.js +130 -0
  145. package/dist/services/delegation-authority.js.map +1 -0
  146. package/dist/services/delegation-trust.d.ts +35 -64
  147. package/dist/services/delegation-trust.d.ts.map +1 -1
  148. package/dist/services/delegation-trust.js +98 -279
  149. package/dist/services/delegation-trust.js.map +1 -1
  150. package/dist/services/delegation.service.d.ts +83 -105
  151. package/dist/services/delegation.service.d.ts.map +1 -1
  152. package/dist/services/delegation.service.js +166 -518
  153. package/dist/services/delegation.service.js.map +1 -1
  154. package/dist/services/idp-token-storage.d.ts +32 -12
  155. package/dist/services/idp-token-storage.d.ts.map +1 -1
  156. package/dist/services/idp-token-storage.js +79 -36
  157. package/dist/services/idp-token-storage.js.map +1 -1
  158. package/dist/services/issuer-keys.d.ts +55 -0
  159. package/dist/services/issuer-keys.d.ts.map +1 -0
  160. package/dist/services/issuer-keys.js +184 -0
  161. package/dist/services/issuer-keys.js.map +1 -0
  162. package/dist/services/oauth-security.service.d.ts +17 -1
  163. package/dist/services/oauth-security.service.d.ts.map +1 -1
  164. package/dist/services/oauth-security.service.js +29 -10
  165. package/dist/services/oauth-security.service.js.map +1 -1
  166. package/dist/services/resource-audience.d.ts +12 -9
  167. package/dist/services/resource-audience.d.ts.map +1 -1
  168. package/dist/services/resource-audience.js +12 -9
  169. package/dist/services/resource-audience.js.map +1 -1
  170. package/dist/services/unenforceable-tool-protection.d.ts +32 -0
  171. package/dist/services/unenforceable-tool-protection.d.ts.map +1 -0
  172. package/dist/services/unenforceable-tool-protection.js +90 -0
  173. package/dist/services/unenforceable-tool-protection.js.map +1 -0
  174. package/dist/services/upstream-fetch.d.ts +14 -0
  175. package/dist/services/upstream-fetch.d.ts.map +1 -0
  176. package/dist/services/upstream-fetch.js +56 -0
  177. package/dist/services/upstream-fetch.js.map +1 -0
  178. package/dist/types.d.ts +5 -18
  179. package/dist/types.d.ts.map +1 -1
  180. package/dist/utils/tool-security-schemes.d.ts +65 -0
  181. package/dist/utils/tool-security-schemes.d.ts.map +1 -0
  182. package/dist/utils/tool-security-schemes.js +168 -0
  183. package/dist/utils/tool-security-schemes.js.map +1 -0
  184. package/package.json +4 -5
  185. package/dist/delegation-http/anchor-do.d.ts +0 -84
  186. package/dist/delegation-http/anchor-do.d.ts.map +0 -1
  187. package/dist/delegation-http/anchor-do.js +0 -412
  188. package/dist/delegation-http/anchor-do.js.map +0 -1
  189. package/dist/delegation-http/anchor-registration-validate.d.ts +0 -61
  190. package/dist/delegation-http/anchor-registration-validate.d.ts.map +0 -1
  191. package/dist/delegation-http/anchor-registration-validate.js +0 -191
  192. package/dist/delegation-http/anchor-registration-validate.js.map +0 -1
  193. package/dist/delegation-http/anchor-registration.d.ts +0 -62
  194. package/dist/delegation-http/anchor-registration.d.ts.map +0 -1
  195. package/dist/delegation-http/anchor-registration.js +0 -337
  196. package/dist/delegation-http/anchor-registration.js.map +0 -1
  197. package/dist/delegation-http/anchor-routing.d.ts +0 -20
  198. package/dist/delegation-http/anchor-routing.d.ts.map +0 -1
  199. package/dist/delegation-http/anchor-routing.js +0 -27
  200. package/dist/delegation-http/anchor-routing.js.map +0 -1
  201. package/dist/delegation-http/challenge-middleware.d.ts +0 -28
  202. package/dist/delegation-http/challenge-middleware.d.ts.map +0 -1
  203. package/dist/delegation-http/challenge-middleware.js +0 -190
  204. package/dist/delegation-http/challenge-middleware.js.map +0 -1
  205. package/dist/delegation-http/challenge.d.ts +0 -102
  206. package/dist/delegation-http/challenge.d.ts.map +0 -1
  207. package/dist/delegation-http/challenge.js +0 -223
  208. package/dist/delegation-http/challenge.js.map +0 -1
  209. package/dist/delegation-http/consent-anchor-bridge.d.ts +0 -70
  210. package/dist/delegation-http/consent-anchor-bridge.d.ts.map +0 -1
  211. package/dist/delegation-http/consent-anchor-bridge.js +0 -1130
  212. package/dist/delegation-http/consent-anchor-bridge.js.map +0 -1
  213. package/dist/delegation-http/consent-preparation-page.d.ts +0 -18
  214. package/dist/delegation-http/consent-preparation-page.d.ts.map +0 -1
  215. package/dist/delegation-http/consent-preparation-page.js +0 -172
  216. package/dist/delegation-http/consent-preparation-page.js.map +0 -1
  217. package/dist/delegation-http/credential-consent.d.ts +0 -149
  218. package/dist/delegation-http/credential-consent.d.ts.map +0 -1
  219. package/dist/delegation-http/credential-consent.js +0 -338
  220. package/dist/delegation-http/credential-consent.js.map +0 -1
  221. package/dist/delegation-http/native-capabilities.d.ts +0 -4
  222. package/dist/delegation-http/native-capabilities.d.ts.map +0 -1
  223. package/dist/delegation-http/native-capabilities.js +0 -53
  224. package/dist/delegation-http/native-capabilities.js.map +0 -1
  225. package/dist/delegation-http/native-oauth-state.d.ts +0 -28
  226. package/dist/delegation-http/native-oauth-state.d.ts.map +0 -1
  227. package/dist/delegation-http/native-oauth-state.js +0 -146
  228. package/dist/delegation-http/native-oauth-state.js.map +0 -1
  229. package/dist/delegation-http/native-oauth.d.ts +0 -26
  230. package/dist/delegation-http/native-oauth.d.ts.map +0 -1
  231. package/dist/delegation-http/native-oauth.js +0 -401
  232. package/dist/delegation-http/native-oauth.js.map +0 -1
  233. package/dist/delegation-http/native-pickup.d.ts +0 -20
  234. package/dist/delegation-http/native-pickup.d.ts.map +0 -1
  235. package/dist/delegation-http/native-pickup.js +0 -227
  236. package/dist/delegation-http/native-pickup.js.map +0 -1
  237. package/dist/delegation-http/pickup-routes.d.ts +0 -43
  238. package/dist/delegation-http/pickup-routes.d.ts.map +0 -1
  239. package/dist/delegation-http/pickup-routes.js +0 -166
  240. package/dist/delegation-http/pickup-routes.js.map +0 -1
  241. package/dist/delegation-http/register.d.ts +0 -26
  242. package/dist/delegation-http/register.d.ts.map +0 -1
  243. package/dist/delegation-http/register.js +0 -95
  244. package/dist/delegation-http/register.js.map +0 -1
  245. package/dist/delegation-http/registrar-auth.d.ts +0 -24
  246. package/dist/delegation-http/registrar-auth.d.ts.map +0 -1
  247. package/dist/delegation-http/registrar-auth.js +0 -61
  248. package/dist/delegation-http/registrar-auth.js.map +0 -1
  249. package/dist/delegation-http/remote-issuer.d.ts +0 -52
  250. package/dist/delegation-http/remote-issuer.d.ts.map +0 -1
  251. package/dist/delegation-http/remote-issuer.js +0 -324
  252. package/dist/delegation-http/remote-issuer.js.map +0 -1
  253. package/dist/delegation-http/types.d.ts +0 -116
  254. package/dist/delegation-http/types.d.ts.map +0 -1
  255. package/dist/delegation-http/types.js +0 -11
  256. package/dist/delegation-http/types.js.map +0 -1
@@ -1,330 +1,169 @@
1
1
  /**
2
2
  * Delegation Service
3
3
  *
4
- * Handles delegation token retrieval, verification, and cache management
5
- * for MCP-I Cloudflare servers.
4
+ * Verifies a presented delegation VC-JWT for MCP-I Cloudflare servers.
6
5
  *
7
- * Supports both:
8
- * - Local VC-JWT verification (offline, cryptographic), restricted to pinned
9
- * issuers and accepted audiences (see ./delegation-trust)
10
- * - Checkpoint API verification (online, centralized)
6
+ * Local verification is the authority (`verifyLocally`): the issuer is the
7
+ * org this resource trusts, its key is the one the token's `kid` names in the
8
+ * org's DID document, the audience is this worker's resource DID, and the
9
+ * status entry is clear on the issuer's own signed list (see
10
+ * ./delegation-trust). Checkpoint is an optional decision hook on top
11
+ * (see ./checkpoint-decision), never the source of authority.
12
+ *
13
+ * Nothing here looks a delegation up by session, user or agent: the client
14
+ * presents the credential on every call.
11
15
  */
12
- import { DEFAULT_CHECKPOINT_URL, DEFAULT_VERIFICATION_CACHE_TTL, DEFAULT_SESSION_CACHE_TTL, } from "../constants";
13
- import { STORAGE_KEYS } from "../constants/storage-keys";
14
- import { parseVCJWT } from "@kya-os/mcp";
15
- import { assertionKeys, audienceVerdict, checkCredentialStatusEntry, credentialHandle, credentialStatusEntries, insecureDevTokensEnabled, isCheckpointPlatformIssuer, resolveDelegationTrust, sharedDelegationDidResolver, verifiesWithAnyKey, } from "./delegation-trust";
16
+ import { askCheckpointDecision } from "./checkpoint-decision";
17
+ import { audienceVerdict, checkCredentialStatusEntry, credentialHandle, credentialStatusEntries, resolveDelegationTrust, } from "./delegation-trust";
18
+ import { decodeJws, resolveIssuerKey, sharedDelegationDidResolver, verifiesWithKey, } from "./issuer-keys";
19
+ import { holderBindingVerdict, isHolderBound, } from "../security/holder-binding";
16
20
  import { RESOURCE_REFUSALS } from "./resource-audience";
17
- /**
18
- * Prefix of a cached development verdict. The rest is the pinned issuer the
19
- * verdict was granted to, re-checked on every hit. Earlier releases cached "1"
20
- * for any self-signed did:key token; those entries never match.
21
- */
22
- const PINNED_VERDICT_PREFIX = "pinned:";
23
21
  /** A token-supplied value, quoted and truncated so it cannot forge log lines. */
24
22
  function logSafe(value) {
25
23
  return JSON.stringify(value.slice(0, 200));
26
24
  }
25
+ const CLOCK_SKEW_SECONDS = 60;
26
+ function isRecord(value) {
27
+ return !!value && typeof value === "object" && !Array.isArray(value);
28
+ }
27
29
  export class DelegationService {
28
30
  env;
29
- runtime;
30
31
  trust;
31
32
  didResolver;
32
- constructor(env, runtime, options = {}) {
33
+ /**
34
+ * @param env - Deployment configuration (trust, audience, Checkpoint hook)
35
+ * @param _runtime - Unused: verification never consults the runtime. Kept
36
+ * so existing `new DelegationService(env, runtime)` callers compile.
37
+ * @param options - Extra pinned issuers and a DID resolution seam
38
+ */
39
+ constructor(env, _runtime, options = {}) {
33
40
  this.env = env;
34
- this.runtime = runtime;
35
41
  this.trust = resolveDelegationTrust(env, options);
36
42
  this.didResolver = options.didResolver ?? sharedDelegationDidResolver();
37
43
  }
38
44
  /**
39
- * Get delegation token from cache or storage
40
- * @param sessionId - Optional session ID for session-based lookup
41
- * @returns Delegation token or null if not found
42
- */
43
- async getDelegationToken(sessionId) {
44
- const delegationStorage = this.env.DELEGATION_STORAGE;
45
- if (!delegationStorage) {
46
- console.error("[Delegation] No delegation storage configured");
47
- return null;
48
- }
49
- try {
50
- // PRIORITY 1: Try user+agent scoped key (user-specific, most secure)
51
- // Get userDid from session if available
52
- let userDid;
53
- let agentDid;
54
- let sessionData = null;
55
- if (sessionId) {
56
- const sessionKey = STORAGE_KEYS.session(sessionId);
57
- sessionData = (await delegationStorage.get(sessionKey, "json"));
58
- userDid = sessionData?.userDid;
59
- agentDid = sessionData?.agentDid;
60
- }
61
- // Get agentDid from runtime if not in session
62
- if (!agentDid && this.runtime) {
63
- const identity = await this.runtime.getIdentity();
64
- agentDid = identity?.did;
65
- }
66
- if (userDid && agentDid) {
67
- const userAgentKey = STORAGE_KEYS.delegation(userDid, agentDid);
68
- console.error("[Delegation] 🔍 PRIORITY 1: Checking user+agent scoped key:", {
69
- key: userAgentKey,
70
- userDid: userDid.slice(0, 20) + "...",
71
- agentDid: agentDid.slice(0, 20) + "...",
72
- });
73
- const userAgentToken = await delegationStorage.get(userAgentKey, "text");
74
- if (userAgentToken) {
75
- const isValid = await this.verifyDelegation(userAgentToken);
76
- if (isValid) {
77
- console.error("[Delegation] ✅ PRIORITY 1: Token retrieved using user+agent DID and verified");
78
- // Re-cache for current session
79
- if (sessionId) {
80
- const sessionKey = STORAGE_KEYS.session(sessionId);
81
- await delegationStorage.put(sessionKey, JSON.stringify({
82
- ...sessionData,
83
- delegationToken: userAgentToken,
84
- userDid,
85
- agentDid,
86
- }), {
87
- expirationTtl: DEFAULT_SESSION_CACHE_TTL,
88
- });
89
- }
90
- return userAgentToken;
91
- }
92
- else {
93
- // Token invalid, remove from cache
94
- await this.invalidateCache(sessionId, userAgentToken, agentDid);
95
- console.error("[Delegation] ⚠️ User+agent token was invalid, removed from cache");
96
- }
97
- }
98
- }
99
- // PRIORITY 2: Try session-scoped token (if session ID was persisted)
100
- if (sessionId && sessionData?.delegationToken) {
101
- console.error("[Delegation] 🔍 PRIORITY 2: Checking session-scoped token:", {
102
- sessionId: sessionId.slice(0, 20) + "...",
103
- });
104
- // Verify token is still valid before returning
105
- const isValid = await this.verifyDelegation(sessionData.delegationToken);
106
- if (isValid) {
107
- console.error("[Delegation] ✅ PRIORITY 2: Token retrieved from session cache and verified");
108
- return sessionData.delegationToken;
109
- }
110
- else {
111
- // Token invalid, remove from cache
112
- await this.invalidateCache(sessionId, sessionData.delegationToken);
113
- console.error("[Delegation] ⚠️ Cached token was invalid, removed from cache");
114
- }
115
- }
116
- // ❌ REMOVED: Legacy agent-scoped fallback (PRIORITY 3)
117
- // This was a security vulnerability that allowed cross-user delegation sharing.
118
- // Delegations are now strictly session-scoped or user+agent scoped.
119
- // Users must complete consent flow for their current session.
120
- console.error("[Delegation] No delegation token found - user must complete consent flow:", {
121
- sessionId: sessionId ? sessionId.slice(0, 20) + "..." : "none",
122
- hasUserDid: !!userDid,
123
- hint: "Delegation tokens are session-scoped. Complete consent flow for this session.",
124
- });
125
- return null;
126
- }
127
- catch (error) {
128
- console.error("[Delegation] Failed to retrieve token:", error);
129
- return null;
130
- }
131
- }
132
- /**
133
- * Check if a token is a VC-JWT (Verifiable Credential JWT)
45
+ * Verify a delegation VC-JWT locally. This is the authority: nothing else
46
+ * can make a credential it refuses valid.
134
47
  *
135
- * VC-JWTs are distinguished from legacy delegation tokens by:
136
- * - alg: 'EdDSA' (Ed25519 signing) vs legacy HS256
137
- * - typ: 'vc+jwt' or 'JWT' (both are valid VC-JWT type indicators), or any
138
- * typ when the payload carries a `vc` object (Checkpoint's own rule), so a
139
- * nonstandard typ cannot route a credential around local verification
140
- *
141
- * This allows legacy HS256 tokens to fall through to API verification
142
- * while VC-JWTs are verified locally using cryptographic verification.
143
- */
144
- isVCJWT(token) {
145
- if (!token || typeof token !== "string")
146
- return false;
147
- try {
148
- // Use parseVCJWT to decode and validate the header
149
- const parsed = parseVCJWT(token);
150
- if (!parsed)
151
- return false;
152
- // VC-JWTs MUST use EdDSA algorithm (Ed25519)
153
- // Legacy tokens use HS256, so this check distinguishes them
154
- if (parsed.header.alg !== "EdDSA")
155
- return false;
156
- // Accept both 'JWT' and 'vc+jwt' as valid type indicators
157
- // W3C VC-JWT spec uses 'vc+jwt', but some implementations use 'JWT'
158
- const validTypes = ["JWT", "vc+jwt"];
159
- const vc = parsed.payload.vc;
160
- return (validTypes.includes(parsed.header.typ) ||
161
- (typeof vc === "object" && vc !== null));
162
- }
163
- catch {
164
- return false;
165
- }
166
- }
167
- /**
168
- * Whether a cached development verdict still holds under THIS deployment's
169
- * trust: the token's issuer is the one the verdict was granted to, it is
170
- * still pinned, and the token's `aud` is still this worker's resource DID
171
- * (a KV namespace may be shared by deployments with different resources).
172
- */
173
- async servesCachedVerdict(token, grantedIssuer) {
174
- const payload = parseVCJWT(token)?.payload;
175
- if (!payload || payload.iss !== grantedIssuer)
176
- return false;
177
- if (audienceVerdict(payload.aud, this.trust) !== "accepted")
178
- return false;
179
- return this.isPinnedIssuer(grantedIssuer);
180
- }
181
- /** Whether `issuerDid` is pinned: statically, or as the Checkpoint platform signer. */
182
- async isPinnedIssuer(issuerDid) {
183
- return (this.trust.issuers.has(issuerDid) ||
184
- (await isCheckpointPlatformIssuer(issuerDid, this.trust, this.didResolver)));
185
- }
186
- /**
187
- * Verify a VC-JWT locally: audience, issuer pin, signature, content and
188
- * credential status, in that order. The cheap checks come first, and the
189
- * only fetch an unpinned issuer can cause is the configured Checkpoint's own
190
- * DID document (cached).
191
- *
192
- * Audience: `aud` must be `did:web:<the host this request was routed for>`,
193
- * and that DID must be in `KYA_OS_RESOURCE_DIDS` (see ./delegation-trust),
194
- * whoever the issuer and whether or not a Checkpoint API key is set. A
195
- * credential without `aud`, or naming anything else (another of this
196
- * worker's hosts, the org DID, the worker's own DID, a project id), is
197
- * refused. Without a valid resource list, or without a routed host (a
198
- * verification with no request behind it), every credential is refused.
199
- *
200
- * Issuer: only pinned issuers are resolved and verified. An untrusted or
201
- * unresolvable issuer fails closed.
48
+ * Checks, cheap ones first so an untrusted token causes no fetch:
49
+ * 1. an EdDSA compact JWS carrying a `vc` object;
50
+ * 2. `aud` names this worker's resource DID;
51
+ * 3. `iss` is a trusted org issuer;
52
+ * 4. the signature verifies under the key the protected `kid` names in
53
+ * the issuer's DID document (assertion methods only; no kid, no key);
54
+ * 5. a DelegationCredential, inside its validity window, whose inner
55
+ * `delegation.constraints.audience` (when present) is also this worker;
56
+ * 6. a status entry, clear on the issuer's own signed list;
57
+ * 7. a holder-bound credential, the holder this call proved
58
+ * (../security/holder-binding).
202
59
  *
203
60
  * @param vcJwt - The VC-JWT string to verify
61
+ * @param options - The call's proved holder, or a deferred holder check
204
62
  * @returns Verification result with extracted delegation data
205
63
  */
206
- async verifyVCJWTLocally(vcJwt) {
207
- const reject = (error) => {
64
+ async verifyLocally(vcJwt, options = {}) {
65
+ const reject = (error, code = "invalid_token") => {
208
66
  console.error("[Delegation] VC-JWT rejected:", error);
209
- return { valid: false, error };
67
+ return { valid: false, error, code };
210
68
  };
211
69
  try {
212
- // 1. Parse the JWT
213
- const parsed = parseVCJWT(vcJwt);
214
- if (!parsed)
70
+ // 1. Shape
71
+ const jws = decodeJws(vcJwt);
72
+ const vc = jws?.payload.vc;
73
+ if (!jws || !isRecord(vc))
215
74
  return reject("VC-JWT parsing failed");
216
- // 2. Issuer DID
217
- const issuerDid = parsed.payload.iss;
218
- if (!issuerDid || typeof issuerDid !== "string")
219
- return reject("Missing issuer (iss)");
220
- // 3. Audience, before anything touches the network
75
+ const { header, payload } = jws;
76
+ // 2. Audience, before anything touches the network
221
77
  if (!this.trust.resourceDid)
222
78
  return reject(RESOURCE_REFUSALS[this.trust.resourceRefusal]);
223
- const audience = audienceVerdict(parsed.payload.aud, this.trust);
79
+ const audience = audienceVerdict(payload.aud, this.trust);
224
80
  if (audience === "missing")
225
81
  return reject("Missing audience (aud)");
226
- if (audience !== "accepted")
82
+ if (audience === "unmatched")
227
83
  return reject("Audience not accepted");
228
- // 4. Issuer pin, before the issuer's DID document is resolved
229
- if (!this.trust.issuers.has(issuerDid) &&
230
- !(await isCheckpointPlatformIssuer(issuerDid, this.trust, this.didResolver))) {
84
+ // 3. Issuer pin, before the issuer's DID document is resolved
85
+ const issuerDid = payload.iss;
86
+ if (typeof issuerDid !== "string" || !issuerDid)
87
+ return reject("Missing issuer (iss)");
88
+ if (!this.trust.issuers.has(issuerDid))
231
89
  return reject(`Untrusted issuer: ${logSafe(issuerDid)}`);
232
- }
233
- // 5. Issuer key, selected by the protected `kid` when present
234
- const kid = parsed.header.kid;
235
- if (kid !== undefined && typeof kid !== "string")
236
- return reject("Malformed key id (kid)");
237
- const didDoc = await this.didResolver.resolve(issuerDid);
238
- const keys = didDoc ? assertionKeys(didDoc, kid) : [];
239
- if (!keys.length)
240
- return reject(`Cannot resolve issuer key: ${logSafe(issuerDid)}`);
241
- // 6. Signature
242
- if (!(await verifiesWithAnyKey(parsed.signingInput, parsed.signature, keys)))
90
+ // 4. Signature under the key the kid names
91
+ if (typeof header.kid !== "string" || !header.kid)
92
+ return reject("Missing key id (kid)");
93
+ const key = await resolveIssuerKey(issuerDid, header.kid, this.didResolver);
94
+ if (!key)
95
+ return reject(`Cannot resolve issuer key ${logSafe(header.kid)} for ${logSafe(issuerDid)}`);
96
+ if (!(await verifiesWithKey(jws.signingInput, jws.signature, key)))
243
97
  return reject("Signature verification failed");
244
- // 7. Run basic VC content validation (type, expiration, required fields)
245
- const vc = parsed.payload.vc;
246
- if (!vc) {
247
- console.error("[Delegation] VC-JWT payload missing vc claim");
248
- return { valid: false, error: "Missing vc claim" };
249
- }
250
- // Validate type
98
+ // 5. Content and validity window
251
99
  const types = vc.type;
252
- if (!types || !Array.isArray(types)) {
253
- console.error("[Delegation] VC-JWT missing type array");
254
- return { valid: false, error: "Missing type array" };
255
- }
256
- if (!types.includes("VerifiableCredential")) {
257
- console.error("[Delegation] VC-JWT missing VerifiableCredential type");
258
- return { valid: false, error: "Missing VerifiableCredential type" };
259
- }
260
- if (!types.includes("DelegationCredential")) {
261
- console.error("[Delegation] VC-JWT missing DelegationCredential type");
262
- return { valid: false, error: "Missing DelegationCredential type" };
263
- }
264
- // Validate expiration (from JWT exp claim or VC expirationDate)
265
- const expClaim = parsed.payload.exp;
100
+ if (!Array.isArray(types) ||
101
+ !types.includes("VerifiableCredential") ||
102
+ !types.includes("DelegationCredential"))
103
+ return reject("Not a DelegationCredential");
104
+ const now = Math.floor(Date.now() / 1000);
105
+ const exp = payload.exp;
106
+ if (exp !== undefined && (typeof exp !== "number" || exp <= now))
107
+ return reject("Token expired (exp claim)", "delegation_expired");
266
108
  const expirationDate = vc.expirationDate;
267
- const now = Date.now();
268
- if (expClaim && expClaim * 1000 < now) {
269
- console.error("[Delegation] VC-JWT expired (exp claim)");
270
- return { valid: false, error: "Token expired (exp claim)" };
271
- }
272
- if (expirationDate && new Date(expirationDate).getTime() < now) {
273
- console.error("[Delegation] VC-JWT expired (expirationDate)");
274
- return { valid: false, error: "Token expired (expirationDate)" };
275
- }
276
- // Validate required fields
277
- if (!vc.credentialSubject) {
278
- console.error("[Delegation] VC-JWT missing credentialSubject");
279
- return { valid: false, error: "Missing credentialSubject" };
280
- }
281
- const credentialSubject = vc.credentialSubject;
282
- if (!credentialSubject.delegation) {
283
- console.error("[Delegation] VC-JWT missing delegation in credentialSubject");
284
- return {
285
- valid: false,
286
- error: "Missing delegation in credentialSubject",
287
- };
288
- }
289
- // 8. Extract delegation data from VC payload
290
- const delegation = credentialSubject.delegation;
291
- // Extract standard JWT claims
292
- const delegationId = credentialHandle(parsed.payload);
293
- const agentDid = parsed.payload.sub || delegation.subjectDid;
294
- // Per RFC 7519, aud can be string or string[] - normalize to string (first element if array)
295
- // CLAIM-SLOT CAVEAT: historically this codebase minted project-scoped
296
- // delegations with aud = project id, which is what "projectId" assumes.
297
- // Cross-resource delegations (delegation-http anchor registration) mint
298
- // aud = the resource ORG's DID instead — for those credentials this value
299
- // is an org DID, not a project id. The audience gate above compares the
300
- // whole claim against every accepted audience; this field is
301
- // attribution only.
302
- const rawAud = parsed.payload.aud;
303
- const projectId = Array.isArray(rawAud) ? rawAud[0] : rawAud;
304
- // Extract delegation-specific fields (Phase 7: userDid, userIdentifier, sessionId, scopes)
305
- const userDid = delegation.userDid;
306
- const userIdentifier = delegation.userIdentifier;
307
- const sessionId = delegation.sessionId;
308
- const scopes = Array.isArray(delegation.scopes)
309
- ? delegation.scopes.filter((s) => typeof s === "string")
109
+ if (typeof expirationDate === "string" &&
110
+ !(Date.parse(expirationDate) / 1000 > now))
111
+ return reject("Token expired (expirationDate)", "delegation_expired");
112
+ const nbf = payload.nbf;
113
+ if (nbf !== undefined &&
114
+ (typeof nbf !== "number" || nbf > now + CLOCK_SKEW_SECONDS))
115
+ return reject("Token not yet valid (nbf claim)", "delegation_not_yet_valid");
116
+ const subject = vc.credentialSubject;
117
+ const delegation = isRecord(subject) ? subject.delegation : undefined;
118
+ if (!isRecord(delegation))
119
+ return reject("Missing delegation in credentialSubject");
120
+ const constraints = isRecord(delegation.constraints)
121
+ ? delegation.constraints
310
122
  : undefined;
311
- // 9. Credential status, fail closed. Status-less credentials rely on the
312
- // Checkpoint confirm for revocation.
313
- const statusEntries = credentialStatusEntries(parsed.payload);
123
+ if (constraints?.audience !== undefined &&
124
+ audienceVerdict(constraints.audience, this.trust) !== "accepted")
125
+ return reject("Inner audience not accepted");
126
+ // 6. Credential status, fail closed
127
+ const statusEntries = credentialStatusEntries(payload);
314
128
  if (!statusEntries)
315
129
  return reject("Malformed credentialStatus");
130
+ if (!statusEntries.length)
131
+ return reject("Missing credentialStatus", "revocation_check_failed");
316
132
  for (const entry of statusEntries) {
317
- const verdict = await checkCredentialStatusEntry(entry);
133
+ const verdict = await checkCredentialStatusEntry(entry, issuerDid, this.didResolver);
318
134
  if (verdict === "revoked")
319
- return reject("Credential revoked");
135
+ return reject("Credential revoked", "delegation_revoked");
320
136
  if (verdict !== "clear")
321
- return reject("Credential status unresolvable");
322
- }
323
- console.error("[Delegation] ✅ VC-JWT verified locally (cryptographic)", {
137
+ return reject("Credential status unresolvable", "revocation_check_failed");
138
+ }
139
+ // 7. Holder binding, from claims the issuer signed: a holder-bound
140
+ // credential needs the holder admission proved for this call.
141
+ const holderBound = isHolderBound(payload);
142
+ if (holderBound && !options.deferHolderBinding) {
143
+ const binding = await holderBindingVerdict(payload, subject.id, options.holderDid);
144
+ if (binding === "holder_proof_required")
145
+ return reject("Holder-bound credential presented without proof of possession", "holder_proof_required");
146
+ if (binding === "holder_mismatch")
147
+ return reject("Credential is bound to another holder", "holder_mismatch");
148
+ }
149
+ const delegationId = credentialHandle(payload);
150
+ const agentDid = (typeof payload.sub === "string" && payload.sub) ||
151
+ (typeof delegation.subjectDid === "string"
152
+ ? delegation.subjectDid
153
+ : undefined);
154
+ if (!agentDid)
155
+ return reject("Missing subject (sub)");
156
+ // The flat grant, as `@kya-os/mcp`'s scope matcher reads it.
157
+ const scopes = [
158
+ ...new Set([delegation.scopes, constraints?.scopes]
159
+ .flatMap((list) => (Array.isArray(list) ? list : []))
160
+ .filter((s) => typeof s === "string")),
161
+ ];
162
+ const userDid = typeof delegation.userDid === "string" ? delegation.userDid : undefined;
163
+ console.error("[Delegation] ✅ VC-JWT verified locally", {
324
164
  delegationId,
325
165
  agentDid: agentDid ? agentDid.slice(0, 20) + "..." : undefined,
326
- userDid: userDid ? userDid.slice(0, 20) + "..." : undefined,
327
- hasSessionId: !!sessionId,
166
+ hasUserDid: !!userDid,
328
167
  scopeCount: scopes?.length,
329
168
  });
330
169
  return {
@@ -332,259 +171,68 @@ export class DelegationService {
332
171
  delegationId,
333
172
  agentDid,
334
173
  userDid,
335
- userIdentifier,
336
- sessionId,
174
+ userIdentifier: typeof delegation.userIdentifier === "string"
175
+ ? delegation.userIdentifier
176
+ : undefined,
177
+ sessionId: typeof delegation.sessionId === "string"
178
+ ? delegation.sessionId
179
+ : undefined,
337
180
  scopes,
338
- projectId,
181
+ projectId: this.trust.resourceDid,
339
182
  issuerDid,
340
- expiresAt: expClaim,
341
- hasCredentialStatus: statusEntries.length > 0,
183
+ expiresAt: typeof exp === "number" ? exp : undefined,
184
+ credential: vc,
185
+ constraints,
186
+ issuedAt: typeof payload.iat === "number" ? payload.iat : undefined,
187
+ amr: Array.isArray(payload.amr)
188
+ ? payload.amr.filter((v) => typeof v === "string")
189
+ : undefined,
190
+ holderBound,
342
191
  };
343
192
  }
344
193
  catch (error) {
345
- console.error("[Delegation] Error during local VC-JWT verification:", error);
346
- return {
347
- valid: false,
348
- error: error instanceof Error ? error.message : "Unknown error",
349
- };
194
+ return reject(error instanceof Error ? error.message : "Verification failed");
350
195
  }
351
196
  }
352
197
  /**
353
- * Check if a JWT token is expired by examining the exp claim.
354
- * This is a lightweight check that doesn't verify signatures.
355
- *
356
- * @param token - JWT token string
357
- * @returns true if token is expired, false otherwise
358
- */
359
- isTokenExpired(token) {
360
- if (!token || typeof token !== "string")
361
- return false;
362
- try {
363
- const parts = token.split(".");
364
- if (parts.length !== 3)
365
- return false;
366
- // Decode payload (second part)
367
- const payloadB64 = parts[1];
368
- // Handle URL-safe base64
369
- const payloadJson = atob(payloadB64.replace(/-/g, "+").replace(/_/g, "/"));
370
- const payload = JSON.parse(payloadJson);
371
- // Check exp claim (seconds since epoch)
372
- if (payload.exp && typeof payload.exp === "number") {
373
- const nowSeconds = Math.floor(Date.now() / 1000);
374
- if (payload.exp < nowSeconds) {
375
- return true;
376
- }
377
- }
378
- return false;
379
- }
380
- catch {
381
- // If we can't parse, don't fail the check - let other validation catch it
382
- return false;
383
- }
384
- }
385
- /**
386
- * Collision-resistant cache-key input for a token: SHA-256 hex of the FULL
387
- * token. NOT a prefix — the first 16 chars of every EdDSA JWT are the
388
- * identical base64url header (`eyJhbGciOiJFZERT` = `{"alg":"EdDSA"`), so a
389
- * prefixed key collides across all EdDSA tokens; one cached positive would
390
- * then admit any forged token. Keying on the full-token digest gives each
391
- * distinct token a distinct cache entry.
392
- */
393
- async hashToken(token) {
394
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
395
- return Array.from(new Uint8Array(digest))
396
- .map((b) => b.toString(16).padStart(2, "0"))
397
- .join("");
398
- }
399
- /**
400
- * Verify delegation token - supports both VC-JWT and legacy tokens
401
- *
402
- * Verification strategy:
403
- * 1. Early expiration check (cheap, before any crypto)
404
- * 2. Check cache (development only, VC-JWTs only)
405
- * 3. If token is a VC-JWT, verify it locally: accepted audience, pinned
406
- * issuer, signature, content and any credentialStatus entry. This refuses
407
- * a forged, foreign or revoked credential with or without Checkpoint.
408
- * 4. Confirm with Checkpoint that the delegation is still in force. A valid
409
- * signature proves who issued the credential, not that it was never
410
- * revoked; revocation of status-less credentials lives at Checkpoint.
411
- * Only a deployment with no Checkpoint API key (development) skips this.
412
- *
413
- * Legacy (non VC-JWT) tokens can only be checked by Checkpoint. Without an
414
- * API key they are refused unless KYA_OS_INSECURE_DEV_TOKENS opts in.
415
- *
416
- * With a Checkpoint API key no verdict is cached: every verification asks
417
- * Checkpoint, so a revocation refuses the very next call. Development caches
418
- * only a pinned issuer's status-less VC-JWT, for
419
- * DEFAULT_VERIFICATION_CACHE_TTL seconds, and a hit counts only while that
420
- * issuer is still pinned.
198
+ * Verify a presented delegation: local verification, then, when this
199
+ * deployment has a Checkpoint API key, the decision hook. Checkpoint can
200
+ * only refuse a locally valid credential for a stateful reason; it can
201
+ * never accept one local verification refused.
421
202
  *
422
203
  * @param token - Delegation token to verify
423
204
  * @returns True if token is valid, false otherwise
424
205
  */
425
206
  async verifyDelegation(token) {
426
- // Early expiration check - reject expired tokens before any other processing
427
- // This is a cheap check that doesn't require crypto or API calls
428
- if (this.isTokenExpired(token)) {
429
- console.error("[Delegation] Token rejected: expired (exp claim)");
207
+ const local = await this.verifyLocally(token);
208
+ // A valid result always names its delegate; the check narrows the type.
209
+ if (!local.valid || !local.agentDid)
430
210
  return false;
431
- }
432
- // Only development (no Checkpoint) caches: a cached positive would outlive
433
- // a revocation at Checkpoint.
434
- const verificationCache = this.env.CHECKPOINT_API_KEY
435
- ? undefined
436
- : this.env.TOOL_PROTECTION_KV;
437
- const isVCJWT = this.isVCJWT(token);
438
- if (verificationCache && isVCJWT) {
439
- const cacheKey = STORAGE_KEYS.verificationCache(await this.hashToken(token));
440
- const cached = await verificationCache.get(cacheKey);
441
- if (typeof cached === "string" &&
442
- cached.startsWith(PINNED_VERDICT_PREFIX) &&
443
- (await this.servesCachedVerdict(token, cached.slice(PINNED_VERDICT_PREFIX.length)))) {
444
- console.error("[Delegation] Token verification cached as valid");
445
- return true;
446
- }
447
- }
448
- let agentDid;
449
- let scopes = [];
450
- let pinnedIssuer;
451
- if (isVCJWT) {
452
- console.error("[Delegation] Detected VC-JWT format, attempting local verification");
453
- const vcResult = await this.verifyVCJWTLocally(token);
454
- if (!vcResult.valid) {
455
- console.error("[Delegation] Local VC-JWT verification failed:", vcResult.error);
456
- return false;
457
- }
458
- agentDid = vcResult.agentDid ?? "";
459
- scopes = vcResult.scopes ?? [];
460
- // A status-bearing credential is re-read every time, so a revocation
461
- // refuses the very next call; only status-less verdicts are cacheable.
462
- pinnedIssuer = vcResult.hasCredentialStatus
463
- ? undefined
464
- : vcResult.issuerDid;
465
- }
466
- else if (!this.env.CHECKPOINT_API_KEY) {
467
- // Nothing local can check a legacy token: it is a bearer string.
468
- if (!insecureDevTokensEnabled(this.env)) {
469
- console.error("[Delegation] Legacy (non VC-JWT) token refused: no CHECKPOINT_API_KEY to verify it. " +
470
- "Set KYA_OS_INSECURE_DEV_TOKENS=1 for local development only.");
471
- return false;
472
- }
473
- console.warn("[Delegation] ⚠️ INSECURE: KYA_OS_INSECURE_DEV_TOKENS is set, so a legacy delegation token " +
474
- "is accepted WITHOUT ANY VERIFICATION. Anyone can forge one. Never enable this outside local development.");
475
- return true; // never cached
476
- }
477
- else {
478
- agentDid = this.runtime ? (await this.runtime.getIdentity()).did : "";
479
- }
480
- if (!this.env.CHECKPOINT_API_KEY) {
481
- console.warn("[Delegation] No Checkpoint API key configured: accepting a pinned, locally verified VC-JWT without Checkpoint, which cannot see revocation of status-less credentials");
482
- }
483
- else if (!(await this.confirmWithCheckpoint(token, agentDid, scopes))) {
211
+ const decision = await askCheckpointDecision(this.env, {
212
+ token,
213
+ agentDid: local.agentDid,
214
+ scopes: [],
215
+ userDid: local.userDid,
216
+ });
217
+ if (decision && !decision.allowed) {
218
+ console.error("[Delegation] Checkpoint decision refused the delegation:", decision.code);
484
219
  return false;
485
220
  }
486
- if (verificationCache && pinnedIssuer) {
487
- const cacheKey = STORAGE_KEYS.verificationCache(await this.hashToken(token));
488
- await verificationCache.put(cacheKey, PINNED_VERDICT_PREFIX + pinnedIssuer, {
489
- expirationTtl: DEFAULT_VERIFICATION_CACHE_TTL,
490
- });
491
- }
492
- console.error("[Delegation] Token verified");
493
221
  return true;
494
222
  }
495
- /**
496
- * Asks Checkpoint whether the delegation behind `token` is in force.
497
- * Checkpoint answers every verification with HTTP 200 and the verdict in
498
- * `data.valid` (a revoked delegation is `valid: false`), so only an explicit
499
- * `valid: true` counts; any other answer or error fails closed.
500
- */
501
- async confirmWithCheckpoint(token, agentDid, scopes) {
502
- const request = { agent_did: agentDid, delegation_token: token, scopes };
503
- try {
504
- // Use AccessControlApiService if available from runtime
505
- if (this.runtime && "accessControlService" in this.runtime) {
506
- const accessControlService = this
507
- .runtime.accessControlService;
508
- if (accessControlService) {
509
- const response = await accessControlService.verifyDelegation(request);
510
- // The runtime client validates its response, but this seam accepts
511
- // any client: only an explicit `true` admits, as on the fetch path.
512
- if (response.data.valid === true)
513
- return true;
514
- console.error("[Delegation] Token verification failed:", response.data.reason || "Invalid token");
515
- return false;
516
- }
517
- }
518
- const checkpointUrl = this.env.CHECKPOINT_API_URL || DEFAULT_CHECKPOINT_URL;
519
- const response = await fetch(`${checkpointUrl}/api/v1/bouncer/delegations/verify`, {
520
- method: "POST",
521
- headers: {
522
- Authorization: `Bearer ${this.env.CHECKPOINT_API_KEY}`,
523
- "Content-Type": "application/json",
524
- },
525
- body: JSON.stringify(request),
526
- });
527
- if (response.status === 401 || response.status === 403) {
528
- console.error("[Delegation] Token verification failed: unauthorized");
529
- return false;
530
- }
531
- if (!response.ok) {
532
- console.warn("[Delegation] Token verification returned unexpected status:", response.status);
533
- return false; // Fail closed for security
534
- }
535
- const body = (await response.json().catch(() => null));
536
- if (body?.data?.valid === true)
537
- return true;
538
- console.error("[Delegation] Token verification failed:", body?.data?.error?.code || "no valid verdict");
539
- return false;
540
- }
541
- catch (error) {
542
- console.error("[Delegation] Error verifying token with Checkpoint:", error);
543
- return false; // Fail closed on errors
544
- }
545
- }
546
- /**
547
- * Invalidate delegation token in all caches
548
- * @param sessionId - Session ID to clear
549
- * @param token - Token to invalidate
550
- * @param agentDid - Agent DID to clear
551
- */
552
- async invalidateCache(sessionId, token, agentDid) {
553
- const delegationStorage = this.env.DELEGATION_STORAGE;
554
- const verificationCache = this.env.TOOL_PROTECTION_KV;
555
- if (!delegationStorage)
556
- return;
557
- const deletions = [];
558
- // Read session data BEFORE scheduling deletion to avoid race condition
559
- let sessionData = null;
560
- if (sessionId) {
561
- const sessionKey = STORAGE_KEYS.session(sessionId);
562
- // Read session data first before scheduling deletion
563
- sessionData = (await delegationStorage.get(sessionKey, "json"));
564
- // Now schedule deletion
565
- deletions.push(delegationStorage.delete(sessionKey));
566
- }
567
- // Clear agent cache (legacy)
568
- if (agentDid) {
569
- const legacyKey = STORAGE_KEYS.legacyDelegation(agentDid);
570
- deletions.push(delegationStorage.delete(legacyKey));
571
- // Use session data we already read (no race condition)
572
- if (sessionData?.userDid) {
573
- const userAgentKey = STORAGE_KEYS.delegation(sessionData.userDid, agentDid);
574
- deletions.push(delegationStorage.delete(userAgentKey));
575
- // Drop the auth-type sidecar with the token it describes, so a later
576
- // delegation for the same user+agent can never inherit a revoked
577
- // delegation's type.
578
- deletions.push(delegationStorage.delete(STORAGE_KEYS.delegationAuthType(sessionData.userDid, agentDid)));
579
- }
580
- }
581
- // Clear verification cache
582
- if (token && verificationCache) {
583
- const cacheKey = STORAGE_KEYS.verificationCache(await this.hashToken(token));
584
- deletions.push(verificationCache.delete(cacheKey));
585
- }
586
- await Promise.all(deletions);
587
- console.error("[Delegation] Cache invalidated for revoked/invalid token");
588
- }
223
+ }
224
+ /**
225
+ * The verifier for one request to a deployment: the environment's trust (the
226
+ * native issuer binding, `KYA_OS_TRUSTED_DELEGATION_ISSUERS`,
227
+ * `KYA_OS_RESOURCE_DIDS`) and the host this request was routed for. Nothing in
228
+ * the runtime configuration adds an issuer, so the edge's bearer check and the
229
+ * Durable Object trust exactly the same issuers. The runtime's verifier and the
230
+ * agent's account lookup both use it, so they apply the same rule.
231
+ */
232
+ export function createDeploymentDelegationService(env, routedHost, didResolver) {
233
+ return new DelegationService(env, undefined, {
234
+ routedHost,
235
+ didResolver,
236
+ });
589
237
  }
590
238
  //# sourceMappingURL=delegation.service.js.map