@kya-os/checkpoint-shared 1.7.0 → 1.9.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 (277) hide show
  1. package/CHANGELOG.md +159 -9
  2. package/README.md +24 -7
  3. package/dist/agent-catalog.d.mts +12 -0
  4. package/dist/agent-catalog.d.mts.map +1 -0
  5. package/dist/agent-catalog.d.ts +12 -0
  6. package/dist/agent-catalog.d.ts.map +1 -0
  7. package/dist/agent-catalog.js +105 -0
  8. package/dist/agent-catalog.mjs +105 -0
  9. package/dist/agent-catalog.mjs.map +1 -0
  10. package/dist/beacon-nonce/index.d.mts +1 -0
  11. package/dist/beacon-nonce/index.d.mts.map +1 -1
  12. package/dist/beacon-nonce/index.d.ts +1 -0
  13. package/dist/beacon-nonce/index.d.ts.map +1 -1
  14. package/dist/beacon-nonce/index.js +9 -3
  15. package/dist/beacon-nonce/index.mjs +9 -4
  16. package/dist/beacon-nonce/index.mjs.map +1 -1
  17. package/dist/beacon-types/index.d.mts +41 -1
  18. package/dist/beacon-types/index.d.mts.map +1 -1
  19. package/dist/beacon-types/index.d.ts +41 -1
  20. package/dist/beacon-types/index.d.ts.map +1 -1
  21. package/dist/beacon-types/index.js +153 -4
  22. package/dist/beacon-types/index.mjs +139 -4
  23. package/dist/beacon-types/index.mjs.map +1 -1
  24. package/dist/{browser-posture-BLhw-MON.d.mts → browser-posture-5fPrsxx7.d.mts} +6 -6
  25. package/dist/{browser-posture-BLhw-MON.d.mts.map → browser-posture-5fPrsxx7.d.mts.map} +1 -1
  26. package/dist/{browser-posture-B8YiPa5c.d.ts → browser-posture-CCR1kh5e.d.ts} +6 -6
  27. package/dist/{browser-posture-B8YiPa5c.d.ts.map → browser-posture-CCR1kh5e.d.ts.map} +1 -1
  28. package/dist/browser-posture-cookie.js +1 -1
  29. package/dist/browser-posture-cookie.mjs +1 -1
  30. package/dist/browser-posture-cookie.mjs.map +1 -1
  31. package/dist/browser-posture-proof-verifier-DvsOmFrM.js +202 -0
  32. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +180 -0
  33. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +1 -0
  34. package/dist/browser-posture-proof-verifier.d.mts +25 -0
  35. package/dist/browser-posture-proof-verifier.d.mts.map +1 -0
  36. package/dist/browser-posture-proof-verifier.d.ts +25 -0
  37. package/dist/browser-posture-proof-verifier.d.ts.map +1 -0
  38. package/dist/browser-posture-proof-verifier.js +7 -0
  39. package/dist/browser-posture-proof-verifier.mjs +3 -0
  40. package/dist/browser-posture-proof.d.mts +4 -5
  41. package/dist/browser-posture-proof.d.mts.map +1 -1
  42. package/dist/browser-posture-proof.d.ts +4 -5
  43. package/dist/browser-posture-proof.d.ts.map +1 -1
  44. package/dist/browser-posture-proof.js +10 -79
  45. package/dist/browser-posture-proof.mjs +6 -77
  46. package/dist/browser-posture-proof.mjs.map +1 -1
  47. package/dist/browser-posture.d.mts +1 -1
  48. package/dist/browser-posture.d.ts +1 -1
  49. package/dist/browser-posture.js +6 -5
  50. package/dist/browser-posture.mjs +4 -3
  51. package/dist/browser-posture.mjs.map +1 -1
  52. package/dist/browser.d.mts +25 -286
  53. package/dist/browser.d.mts.map +1 -1
  54. package/dist/browser.d.ts +25 -286
  55. package/dist/browser.d.ts.map +1 -1
  56. package/dist/browser.js +1 -1
  57. package/dist/browser.mjs +1 -1
  58. package/dist/browser.mjs.map +1 -1
  59. package/dist/canonical-signer/index.js +30 -28
  60. package/dist/canonical-signer/index.mjs +31 -1
  61. package/dist/canonical-signer/index.mjs.map +1 -1
  62. package/dist/clearance.d.mts +1 -1
  63. package/dist/clearance.d.ts +1 -1
  64. package/dist/clearance.js +2 -2
  65. package/dist/clearance.mjs +2 -2
  66. package/dist/client-ip-B7w-uHfS.d.mts +55 -0
  67. package/dist/client-ip-B7w-uHfS.d.mts.map +1 -0
  68. package/dist/client-ip-B7w-uHfS.d.ts +55 -0
  69. package/dist/client-ip-B7w-uHfS.d.ts.map +1 -0
  70. package/dist/{client-ip-CW6pRyLf.js → client-ip-B8wFzJ5f.js} +117 -7
  71. package/dist/{client-ip-B2Xeo-GK.mjs → client-ip-DIJyr6px.mjs} +113 -9
  72. package/dist/client-ip-DIJyr6px.mjs.map +1 -0
  73. package/dist/client-ip.d.mts +2 -2
  74. package/dist/client-ip.d.ts +2 -2
  75. package/dist/client-ip.js +3 -2
  76. package/dist/client-ip.mjs +2 -2
  77. package/dist/consent-handoff.d.mts +0 -3
  78. package/dist/consent-handoff.d.mts.map +1 -1
  79. package/dist/consent-handoff.d.ts +0 -3
  80. package/dist/consent-handoff.d.ts.map +1 -1
  81. package/dist/consent-handoff.mjs.map +1 -1
  82. package/dist/default-sign-in-host.d.mts +10 -0
  83. package/dist/default-sign-in-host.d.mts.map +1 -0
  84. package/dist/default-sign-in-host.d.ts +10 -0
  85. package/dist/default-sign-in-host.d.ts.map +1 -0
  86. package/dist/default-sign-in-host.js +72 -0
  87. package/dist/default-sign-in-host.mjs +66 -0
  88. package/dist/default-sign-in-host.mjs.map +1 -0
  89. package/dist/detection-reason-mapping-B9RSkOs8.js +277 -0
  90. package/dist/detection-reason-mapping-BGymWIPl.mjs +249 -0
  91. package/dist/detection-reason-mapping-BGymWIPl.mjs.map +1 -0
  92. package/dist/detection-reason-mapping-CQexNvR7.d.mts +52 -0
  93. package/dist/detection-reason-mapping-CQexNvR7.d.mts.map +1 -0
  94. package/dist/detection-reason-mapping-CQexNvR7.d.ts +52 -0
  95. package/dist/detection-reason-mapping-CQexNvR7.d.ts.map +1 -0
  96. package/dist/engine-enforcing-AYEcgNsb.js +39 -0
  97. package/dist/engine-enforcing-B5eNfCpG.mjs +29 -0
  98. package/dist/engine-enforcing-B5eNfCpG.mjs.map +1 -0
  99. package/dist/engine-enforcing-DiOclGqf.d.mts +11 -0
  100. package/dist/engine-enforcing-DiOclGqf.d.mts.map +1 -0
  101. package/dist/engine-enforcing-DiOclGqf.d.ts +11 -0
  102. package/dist/engine-enforcing-DiOclGqf.d.ts.map +1 -0
  103. package/dist/engine-info.d.mts +2 -0
  104. package/dist/engine-info.d.ts +2 -0
  105. package/dist/engine-info.js +4 -0
  106. package/dist/engine-info.mjs +3 -0
  107. package/dist/errors/index.d.mts +6 -0
  108. package/dist/errors/index.d.mts.map +1 -1
  109. package/dist/errors/index.d.ts +6 -0
  110. package/dist/errors/index.d.ts.map +1 -1
  111. package/dist/errors/index.js +28 -6
  112. package/dist/errors/index.mjs +28 -6
  113. package/dist/errors/index.mjs.map +1 -1
  114. package/dist/{external-B7WI9FyQ.d.ts → external-m3Kmafwj.d.mts} +2 -2
  115. package/dist/{external-B7WI9FyQ.d.mts.map → external-m3Kmafwj.d.mts.map} +1 -1
  116. package/dist/{external-B7WI9FyQ.d.mts → external-m3Kmafwj.d.ts} +2 -2
  117. package/dist/{external-B7WI9FyQ.d.ts.map → external-m3Kmafwj.d.ts.map} +1 -1
  118. package/dist/fetcher-C8qvwdnA.d.ts +44 -0
  119. package/dist/fetcher-C8qvwdnA.d.ts.map +1 -0
  120. package/dist/fetcher-D2vjr7jB.d.mts +44 -0
  121. package/dist/fetcher-D2vjr7jB.d.mts.map +1 -0
  122. package/dist/gateway-client-ip.d.mts +1 -3
  123. package/dist/gateway-client-ip.d.mts.map +1 -1
  124. package/dist/gateway-client-ip.d.ts +1 -3
  125. package/dist/gateway-client-ip.d.ts.map +1 -1
  126. package/dist/gateway-client-ip.js +2 -2
  127. package/dist/gateway-client-ip.mjs +2 -2
  128. package/dist/gateway-client-ip.mjs.map +1 -1
  129. package/dist/host-adapter/index.d.mts +2 -2
  130. package/dist/host-adapter/index.d.ts +2 -2
  131. package/dist/host-adapter/index.js +2 -1
  132. package/dist/host-adapter/index.mjs +2 -2
  133. package/dist/{host-adapter-C-4IxmqM.mjs → host-adapter-BKdQHwbi.mjs} +56 -3
  134. package/dist/{host-adapter-C-4IxmqM.mjs.map → host-adapter-BKdQHwbi.mjs.map} +1 -1
  135. package/dist/{host-adapter-CwW9YB0U.js → host-adapter-bWftXA9T.js} +60 -1
  136. package/dist/index-DnFsmr_o.d.ts +156 -0
  137. package/dist/index-DnFsmr_o.d.ts.map +1 -0
  138. package/dist/index-rvw5Bz-r.d.mts +156 -0
  139. package/dist/index-rvw5Bz-r.d.mts.map +1 -0
  140. package/dist/index.d.mts +6681 -11335
  141. package/dist/index.d.mts.map +1 -1
  142. package/dist/index.d.ts +6681 -11335
  143. package/dist/index.d.ts.map +1 -1
  144. package/dist/index.js +2322 -6900
  145. package/dist/index.mjs +2236 -6574
  146. package/dist/index.mjs.map +1 -1
  147. package/dist/{kya-http-error-codes-UYb1zpGM.js → kya-http-error-codes-B4rUmUEI.js} +2 -0
  148. package/dist/{kya-http-error-codes-7ewV5RuK.d.ts → kya-http-error-codes-C14E4gi3.d.mts} +2 -1
  149. package/dist/kya-http-error-codes-C14E4gi3.d.mts.map +1 -0
  150. package/dist/{kya-http-error-codes-7ewV5RuK.d.mts → kya-http-error-codes-C14E4gi3.d.ts} +2 -1
  151. package/dist/kya-http-error-codes-C14E4gi3.d.ts.map +1 -0
  152. package/dist/{kya-http-error-codes-C2JiWPsi.mjs → kya-http-error-codes-DSBrxNry.mjs} +3 -1
  153. package/dist/kya-http-error-codes-DSBrxNry.mjs.map +1 -0
  154. package/dist/kya-http.d.mts +3 -3
  155. package/dist/kya-http.d.ts +3 -3
  156. package/dist/kya-http.js +10 -2
  157. package/dist/kya-http.mjs +4 -3
  158. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  159. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  160. package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
  161. package/dist/mcpi/status-list/index.d.mts +72 -0
  162. package/dist/mcpi/status-list/index.d.mts.map +1 -0
  163. package/dist/mcpi/status-list/index.d.ts +72 -0
  164. package/dist/mcpi/status-list/index.d.ts.map +1 -0
  165. package/dist/mcpi/status-list/index.js +703 -0
  166. package/dist/mcpi/status-list/index.mjs +684 -0
  167. package/dist/mcpi/status-list/index.mjs.map +1 -0
  168. package/dist/patterns-Bp40cwh2.d.mts +110 -0
  169. package/dist/patterns-Bp40cwh2.d.mts.map +1 -0
  170. package/dist/patterns-Bp40cwh2.d.ts +110 -0
  171. package/dist/patterns-Bp40cwh2.d.ts.map +1 -0
  172. package/dist/patterns-CiMpbdAF.js +243 -0
  173. package/dist/patterns-D4OAsNQY.mjs +173 -0
  174. package/dist/patterns-D4OAsNQY.mjs.map +1 -0
  175. package/dist/patterns.d.mts +2 -0
  176. package/dist/patterns.d.ts +2 -0
  177. package/dist/patterns.js +15 -0
  178. package/dist/patterns.mjs +3 -0
  179. package/dist/policy/enforcement.d.mts +3 -2
  180. package/dist/policy/enforcement.d.ts +3 -2
  181. package/dist/policy/enforcement.js +8 -2
  182. package/dist/policy/enforcement.mjs +3 -2
  183. package/dist/policy/fetcher.d.mts +2 -0
  184. package/dist/policy/fetcher.d.ts +2 -0
  185. package/dist/policy/fetcher.js +240 -0
  186. package/dist/policy/fetcher.mjs +238 -0
  187. package/dist/policy/fetcher.mjs.map +1 -0
  188. package/dist/policy/schemas.d.mts +3 -0
  189. package/dist/policy/schemas.d.ts +3 -0
  190. package/dist/policy/schemas.js +27 -0
  191. package/dist/policy/schemas.mjs +4 -0
  192. package/dist/{posture-origins-Ba83O0cD.mjs → posture-origins-Ci6k4Zh1.js} +24 -173
  193. package/dist/{posture-origins-CdVOdiMT.js → posture-origins-DGyS4Vuk.mjs} +2 -267
  194. package/dist/posture-origins-DGyS4Vuk.mjs.map +1 -0
  195. package/dist/{project-verification-key-BccT12tQ.js → project-verification-key-B-L3D2nC.js} +1 -1
  196. package/dist/{project-verification-key-66N4edKn.mjs → project-verification-key-CWXdu3-n.mjs} +2 -2
  197. package/dist/{project-verification-key-66N4edKn.mjs.map → project-verification-key-CWXdu3-n.mjs.map} +1 -1
  198. package/dist/provider-registry.d.mts +2 -0
  199. package/dist/provider-registry.d.ts +2 -0
  200. package/dist/provider-registry.js +51 -0
  201. package/dist/provider-registry.mjs +3 -0
  202. package/dist/reason-codes.d.mts +2 -0
  203. package/dist/reason-codes.d.ts +2 -0
  204. package/dist/reason-codes.js +8 -0
  205. package/dist/reason-codes.mjs +3 -0
  206. package/dist/{registered-sid-hUl-bvM5.mjs → registered-sid-26hNxp6t.mjs} +11 -2
  207. package/dist/registered-sid-26hNxp6t.mjs.map +1 -0
  208. package/dist/registered-sid-D6KCaT1E.d.mts +33 -0
  209. package/dist/registered-sid-D6KCaT1E.d.mts.map +1 -0
  210. package/dist/registered-sid-D6KCaT1E.d.ts +33 -0
  211. package/dist/registered-sid-D6KCaT1E.d.ts.map +1 -0
  212. package/dist/{registered-sid-eLCNZvIF.js → registered-sid-DVGTSH0L.js} +15 -0
  213. package/dist/ruleset-hash-Cmv8MSO5.js +34 -0
  214. package/dist/ruleset-hash-IRN5eI9H.d.mts +5 -0
  215. package/dist/ruleset-hash-IRN5eI9H.d.mts.map +1 -0
  216. package/dist/ruleset-hash-IRN5eI9H.d.ts +5 -0
  217. package/dist/ruleset-hash-IRN5eI9H.d.ts.map +1 -0
  218. package/dist/ruleset-hash-QQIaLuPi.mjs +30 -0
  219. package/dist/ruleset-hash-QQIaLuPi.mjs.map +1 -0
  220. package/dist/{schemas-YhagYDx_.js → schemas-BlScS1it.js} +0 -20
  221. package/dist/{index-HaqfPtaL.d.ts → schemas-CGKHzcMV.d.ts} +23 -195
  222. package/dist/schemas-CGKHzcMV.d.ts.map +1 -0
  223. package/dist/schemas-Cm4C4Z5G.js +703 -0
  224. package/dist/schemas-DPIT8usF.mjs +525 -0
  225. package/dist/schemas-DPIT8usF.mjs.map +1 -0
  226. package/dist/{schemas-7qodsG-Z.mjs → schemas-IHAhH3gV.mjs} +2 -16
  227. package/dist/schemas-IHAhH3gV.mjs.map +1 -0
  228. package/dist/{index-B7rTovHa.d.mts → schemas-m-GqyfyO.d.mts} +23 -195
  229. package/dist/schemas-m-GqyfyO.d.mts.map +1 -0
  230. package/dist/{step-up-COlmWJN8.mjs → step-up-BK0oBi11.mjs} +91 -41
  231. package/dist/step-up-BK0oBi11.mjs.map +1 -0
  232. package/dist/{step-up-C2d8C20x.js → step-up-Bp8RAQwv.js} +117 -55
  233. package/dist/{step-up-BjP--hG-.d.mts → step-up-Bz12gYKT.d.mts} +28 -12
  234. package/dist/step-up-Bz12gYKT.d.mts.map +1 -0
  235. package/dist/{step-up-BjP--hG-.d.ts → step-up-Bz12gYKT.d.ts} +28 -12
  236. package/dist/step-up-Bz12gYKT.d.ts.map +1 -0
  237. package/dist/test-fixtures/index.d.mts +4 -4
  238. package/dist/test-fixtures/index.d.mts.map +1 -1
  239. package/dist/test-fixtures/index.d.ts +4 -4
  240. package/dist/test-fixtures/index.d.ts.map +1 -1
  241. package/dist/test-fixtures/index.js +4 -4
  242. package/dist/test-fixtures/index.mjs +4 -4
  243. package/dist/test-fixtures/index.mjs.map +1 -1
  244. package/dist/tool-protection/index.d.mts +12 -0
  245. package/dist/tool-protection/index.d.mts.map +1 -1
  246. package/dist/tool-protection/index.d.ts +12 -0
  247. package/dist/tool-protection/index.d.ts.map +1 -1
  248. package/dist/tool-protection/index.js +46 -0
  249. package/dist/tool-protection/index.mjs +44 -1
  250. package/dist/tool-protection/index.mjs.map +1 -1
  251. package/dist/verification-BAw9N8Pt.js +181 -0
  252. package/dist/verification-Cvvv86TT.mjs +123 -0
  253. package/dist/verification-Cvvv86TT.mjs.map +1 -0
  254. package/fixtures/client-ip-resolution.n01.json +101 -0
  255. package/fixtures/kya-http/error-codes.json +2 -1
  256. package/fixtures/reviewer-grant-revocation.v1.json +53 -81
  257. package/package.json +55 -4
  258. package/dist/client-ip-B2Xeo-GK.mjs.map +0 -1
  259. package/dist/client-ip-DFamiNoz.d.mts +0 -34
  260. package/dist/client-ip-DFamiNoz.d.mts.map +0 -1
  261. package/dist/client-ip-DFamiNoz.d.ts +0 -34
  262. package/dist/client-ip-DFamiNoz.d.ts.map +0 -1
  263. package/dist/index-B7rTovHa.d.mts.map +0 -1
  264. package/dist/index-HaqfPtaL.d.ts.map +0 -1
  265. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +0 -1
  266. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +0 -1
  267. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +0 -1
  268. package/dist/posture-origins-Ba83O0cD.mjs.map +0 -1
  269. package/dist/registered-sid-D3g-gZQF.d.mts +0 -11
  270. package/dist/registered-sid-D3g-gZQF.d.mts.map +0 -1
  271. package/dist/registered-sid-D3g-gZQF.d.ts +0 -11
  272. package/dist/registered-sid-D3g-gZQF.d.ts.map +0 -1
  273. package/dist/registered-sid-hUl-bvM5.mjs.map +0 -1
  274. package/dist/schemas-7qodsG-Z.mjs.map +0 -1
  275. package/dist/step-up-BjP--hG-.d.mts.map +0 -1
  276. package/dist/step-up-BjP--hG-.d.ts.map +0 -1
  277. package/dist/step-up-COlmWJN8.mjs.map +0 -1
@@ -1,5 +1,48 @@
1
1
  import { z } from "zod";
2
2
 
3
+ //#region src/tool-protection/default-required-scopes.ts
4
+ /** The longest scope a consent request carries. */
5
+ const MAX_DEFAULT_SCOPE_LENGTH = 200;
6
+ const EXECUTE_SUFFIX = ":execute";
7
+ /** Outside the RFC 6749 scope-token alphabet: printable ASCII except space, `"` and `\`. */
8
+ const NON_SCOPE_TOKEN_CHARS = /[^\x21\x23-\x5B\x5D-\x7E]/gu;
9
+ function scopeList(value) {
10
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string") ? value : void 0;
11
+ }
12
+ function declaredOauthScopes(schemes) {
13
+ if (!Array.isArray(schemes)) return [];
14
+ const scopes = schemes.flatMap((scheme) => typeof scheme === "object" && scheme !== null && scheme.type === "oauth2" && Array.isArray(scheme.scopes) ? scheme.scopes.filter((scope) => typeof scope === "string" && scope.length > 0) : []);
15
+ return [...new Set(scopes)];
16
+ }
17
+ /**
18
+ * `<name>:execute`, with the name reduced to the scope-token alphabet (the edge
19
+ * drops other characters) and the whole scope at most
20
+ * {@link MAX_DEFAULT_SCOPE_LENGTH} characters.
21
+ */
22
+ function executeScopeFor(toolName) {
23
+ return `${toolName.replace(NON_SCOPE_TOKEN_CHARS, "_").slice(0, 192)}${EXECUTE_SUFFIX}`;
24
+ }
25
+ /**
26
+ * The scopes to store for `toolName`: the first non-empty of
27
+ *
28
+ * 1. the entry's own `requiredScopes`, as stored;
29
+ * 2. its legacy `scopes`, so a grant for the scope the runtime reported keeps matching;
30
+ * 3. the oauth2 scopes its `securitySchemes` declare;
31
+ * 4. its `capability`;
32
+ * 5. {@link executeScopeFor}`(toolName)`.
33
+ *
34
+ * Never empty. An absent entry gets the last.
35
+ */
36
+ function defaultRequiredScopes(toolName, entry) {
37
+ const own = scopeList(entry?.requiredScopes) ?? scopeList(entry?.scopes);
38
+ if (own) return [...own];
39
+ const declared = declaredOauthScopes(entry?.securitySchemes);
40
+ if (declared.length > 0) return declared;
41
+ if (typeof entry?.capability === "string" && entry.capability.length > 0) return [entry.capability];
42
+ return [executeScopeFor(toolName)];
43
+ }
44
+
45
+ //#endregion
3
46
  //#region src/tool-protection/index.ts
4
47
  /**
5
48
  * KYA-OS Tool Protection Specification
@@ -417,5 +460,5 @@ function normalizeAuthorizationType(auth, options = {}) {
417
460
  }
418
461
 
419
462
  //#endregion
420
- export { AUTHORIZATION_TYPES, AuthRequiredError, AuthRequiredErrorDataSchema, AuthorizationRequirementSchema, CONSENT_PROVIDER_TYPES, DelegationRequiredErrorDataSchema, ToolProtectionMapSchema, ToolProtectionResponseSchema, ToolProtectionSchema, createDelegationRequiredError, determineConsentProviderType, getAuthorizationTypeKey, getAuthorizationTypeLabel, getToolRequiredScopes, getToolRiskLevel, hasApiKeyAuthorization, hasOAuthAuthorization, hasPasswordAuthorization, hasVerifiableCredentialAuthorization, isAuthorizationRequirement, isDelegationRequiredErrorData, isToolProtection, isToolProtectionMap, isToolProtectionResponse, normalizeAuthorizationType, normalizeToolProtection, toolRequiresDelegation, validateDelegationRequiredErrorData, validateToolProtection, validateToolProtectionMap, validateToolProtectionResponse };
463
+ export { AUTHORIZATION_TYPES, AuthRequiredError, AuthRequiredErrorDataSchema, AuthorizationRequirementSchema, CONSENT_PROVIDER_TYPES, DelegationRequiredErrorDataSchema, MAX_DEFAULT_SCOPE_LENGTH, ToolProtectionMapSchema, ToolProtectionResponseSchema, ToolProtectionSchema, createDelegationRequiredError, defaultRequiredScopes, determineConsentProviderType, executeScopeFor, getAuthorizationTypeKey, getAuthorizationTypeLabel, getToolRequiredScopes, getToolRiskLevel, hasApiKeyAuthorization, hasOAuthAuthorization, hasPasswordAuthorization, hasVerifiableCredentialAuthorization, isAuthorizationRequirement, isDelegationRequiredErrorData, isToolProtection, isToolProtectionMap, isToolProtectionResponse, normalizeAuthorizationType, normalizeToolProtection, toolRequiresDelegation, validateDelegationRequiredErrorData, validateToolProtection, validateToolProtectionMap, validateToolProtectionResponse };
421
464
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/tool-protection/index.ts"],"sourcesContent":["/**\n * KYA-OS Tool Protection Specification\n *\n * Core types for tool protection with delegation requirements.\n *\n * Consent Flow: type='none' → 2 screens, others → 3 screens (Auth→Consent→Success).\n * DelegationCredential (VC) is created when user confirms on Consent Screen.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/tool-protection` as part\n * of the E6 / C-series decommission (#2914 / #2917): checkpoint owns its product\n * types now that the DIF `@kya-os/mcp` core is protocol-only. The single external\n * dependency (`envVarNameSchema` from the contracts `vault` module) is inlined\n * below so this module pulls nothing from `@kya-os/contracts`.\n *\n * @module @kya-os/checkpoint-shared/tool-protection\n */\n\nimport { z } from 'zod';\n\n/**\n * Pattern for valid environment variable names (e.g., X_API_KEY, OPENAI_KEY).\n * Inlined from the former `@kya-os/contracts/vault` `ENV_VAR_PATTERN`.\n */\nconst ENV_VAR_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\n/**\n * Validates an env var name used by the `apikey` authorization requirement.\n * Inlined from the former `@kya-os/contracts/vault` `envVarNameSchema`.\n */\nconst envVarNameSchema = z\n .string()\n .regex(ENV_VAR_PATTERN, 'Must be a valid env var name (e.g., X_API_KEY)')\n .max(255);\n\n/**\n * Authorization Requirement - what auth is needed BEFORE consent screen.\n *\n * Types: none (2 screens), oauth/password/mdl/idv (3 screens), verifiable_credential (future).\n * The VC output is always a DelegationCredential created on consent confirmation.\n */\nexport type AuthorizationRequirement =\n | {\n /**\n * @deprecated Use 'oauth2' instead. Will be removed in v2.0.0.\n */\n type: 'oauth';\n provider: string; // \"github\", \"google\", etc.\n requiredScopes?: string[]; // Provider-specific scopes\n }\n | {\n /** OAuth 2.0 provider authentication (canonical) */\n type: 'oauth2';\n provider: string; // \"github\", \"google\", etc.\n requiredScopes?: string[]; // Provider-specific scopes\n }\n | {\n type: 'password';\n provider: string; // Credential provider ID (e.g., \"hardwareworld\", \"custom\")\n }\n | {\n type: 'mdl';\n issuer: string; // MDL issuer DID or identifier\n credentialType?: string; // Specific MDL credential type\n }\n | {\n type: 'idv';\n provider: string; // IDV provider name\n verificationLevel?: 'basic' | 'enhanced' | 'loa3';\n }\n | {\n /** Require user to present an existing VC */\n type: 'verifiable_credential';\n credentialType: string;\n issuer?: string;\n }\n | {\n /**\n * @deprecated Use 'verifiable_credential' instead. Will be removed in v2.0.0.\n * This is an alias for 'verifiable_credential' for backward compatibility.\n */\n type: 'credential';\n credentialType: string;\n issuer?: string;\n }\n | {\n /** WebAuthn/Passkey authentication */\n type: 'webauthn';\n rpId?: string; // Relying Party ID\n userVerification?: 'required' | 'preferred' | 'discouraged';\n }\n | {\n /** Sign-In with Ethereum (EIP-4361) */\n type: 'siwe';\n chainId?: number; // Ethereum chain ID (1 = mainnet, 137 = polygon, etc.)\n domain?: string; // Domain for SIWE message\n }\n | {\n /** API Key from per-user vault */\n type: 'apikey';\n envVarNames: string[]; // Env var names to resolve from vault (e.g., ['X_API_KEY'])\n headerMapping: Record<string, string>; // Map env var → HTTP header (e.g., { X_API_KEY: 'X-API-Key' })\n }\n | {\n type: 'none'; // Just consent checkbox, no external auth\n };\n\n/** Canonical authorization type values for type safety */\nexport const AUTHORIZATION_TYPES = {\n /** @deprecated Use OAUTH2 instead. Will be removed in v2.0.0. */\n OAUTH: 'oauth',\n /** OAuth 2.0 provider authentication (canonical) */\n OAUTH2: 'oauth2',\n PASSWORD: 'password',\n MDL: 'mdl',\n IDV: 'idv',\n VERIFIABLE_CREDENTIAL: 'verifiable_credential',\n /** WebAuthn/Passkey authentication */\n WEBAUTHN: 'webauthn',\n /** Sign-In with Ethereum (EIP-4361) */\n SIWE: 'siwe',\n /** API Key from per-user vault */\n APIKEY: 'apikey',\n NONE: 'none',\n} as const;\n\nexport type AuthorizationType = (typeof AUTHORIZATION_TYPES)[keyof typeof AUTHORIZATION_TYPES];\n\n/**\n * Tool Protection Definition\n *\n * Defines the protection requirements for a tool as per KYA-OS spec.\n * This is the canonical definition that all implementations must follow.\n */\nexport interface ToolProtection {\n /**\n * Whether this tool requires explicit delegation from the user\n */\n requiresDelegation: boolean;\n\n /**\n * The scopes required to execute this tool\n * Format: \"resource:action\" (e.g., \"files:read\", \"payment:send\")\n */\n requiredScopes: string[];\n\n /**\n * Risk level classification for the tool\n * Used to determine appropriate authorization flows\n */\n riskLevel?: 'low' | 'medium' | 'high' | 'critical';\n\n /**\n * OAuth provider name for this tool (Phase 2+)\n * If specified, this tool will use the specified OAuth provider.\n * If not specified, provider will be resolved via fallback strategies.\n * @example \"github\", \"google\", \"microsoft\"\n * @deprecated Use `authorization` field instead. Will be removed in Phase 3.\n */\n oauthProvider?: string;\n\n /**\n * Authorization requirement for this tool\n * If requiresDelegation=true, authorization must be specified (or inferred from legacy fields)\n */\n authorization?: AuthorizationRequirement;\n}\n\n/**\n * Tool Protection Map\n *\n * A mapping of tool names to their protection configurations.\n * This is how tool protections are typically stored and transmitted.\n */\nexport type ToolProtectionMap = Record<string, ToolProtection>;\n\n/**\n * Partial tool protection for updates (all fields optional)\n * Use this when accepting partial updates to tool protection settings\n */\nexport type PartialToolProtection = Partial<ToolProtection>;\n\n/**\n * Tool protection with explicit optional fields\n * Useful when TypeScript's Partial<T> doesn't preserve optional property access\n * Supports explicit null values to clear fields\n */\nexport type ToolProtectionUpdate = {\n requiresDelegation?: boolean;\n requiredScopes?: string[];\n riskLevel?: 'low' | 'medium' | 'high' | 'critical';\n oauthProvider?: string | null; // null explicitly clears the field\n authorization?: AuthorizationRequirement | null; // null explicitly clears the field\n};\n\n/**\n * Tool Protection Response\n *\n * The response format when querying for tool protections.\n * Used by tool protection services and APIs.\n */\nexport interface ToolProtectionResponse {\n /**\n * The tool protections keyed by tool name\n */\n toolProtections: ToolProtectionMap;\n\n /**\n * Optional metadata about the response\n */\n metadata?: {\n /**\n * When this configuration was last updated\n */\n lastUpdated?: string;\n\n /**\n * Version of the configuration\n */\n version?: string;\n\n /**\n * Source of the configuration\n */\n source?: string;\n };\n}\n\n/**\n * Delegation Required Error Data\n *\n * The standardized error data returned when a tool requires delegation\n * but none was provided. This is part of the KYA-OS error protocol.\n */\nexport interface DelegationRequiredErrorData {\n /**\n * The name of the tool that requires delegation\n */\n toolName: string;\n\n /**\n * The scopes required for this tool\n */\n requiredScopes: string[];\n\n /**\n * URL where the user can provide consent/delegation\n */\n consentUrl?: string;\n\n /**\n * Alternative field for consent URL (for compatibility)\n */\n authorizationUrl?: string;\n\n /**\n * Additional context about why delegation is required\n */\n reason?: string;\n}\n\n/**\n * Auth Required Error Data\n *\n * Machine-readable error returned when a tool requires per-user auth\n * (vault secret, OAuth, credential) but none is configured and no\n * static env fallback exists. MCP clients use this to present\n * actionable guidance (e.g., \"Add your PulseMCP API key\" with a link).\n *\n * Closes VAULT-11\n */\nexport interface AuthRequiredErrorData {\n /** Discriminator — always \"auth_required\" */\n error: 'auth_required';\n\n /** Which auth mechanism is missing */\n type: 'apikey' | 'oauth' | 'credential';\n\n /** For apikey: which env vars are missing */\n envVarNames?: string[];\n\n /** Dashboard URL where the user can configure the missing auth */\n configUrl: string;\n\n /** Human-readable fallback message */\n message: string;\n}\n\nexport const AuthRequiredErrorDataSchema = z.object({\n error: z.literal('auth_required'),\n type: z.enum(['apikey', 'oauth', 'credential']),\n envVarNames: z.array(z.string()).optional(),\n configUrl: z.string(),\n message: z.string(),\n});\n\n/**\n * Error class thrown when required auth is missing and no fallback exists.\n *\n * Caught by the tool-call handler in agent.ts and serialized as a\n * machine-readable MCP tool result so clients can present actionable UI.\n */\nexport class AuthRequiredError extends Error {\n public readonly type: AuthRequiredErrorData['type'];\n public readonly envVarNames?: string[];\n public readonly configUrl: string;\n\n constructor(opts: {\n type: AuthRequiredErrorData['type'];\n envVarNames?: string[];\n configUrl: string;\n message?: string;\n }) {\n const message =\n opts.message ??\n (opts.type === 'apikey' && opts.envVarNames?.length\n ? `API key required: configure ${opts.envVarNames.join(', ')} in your project settings.`\n : 'Authentication required to use this tool.');\n super(message);\n this.name = 'AuthRequiredError';\n this.type = opts.type;\n this.envVarNames = opts.envVarNames;\n this.configUrl = opts.configUrl;\n }\n\n /** Serialize to the wire format MCP clients expect */\n toJSON(): AuthRequiredErrorData {\n return {\n error: 'auth_required',\n type: this.type,\n ...(this.envVarNames && { envVarNames: this.envVarNames }),\n configUrl: this.configUrl,\n message: this.message,\n };\n }\n}\n\n/**\n * Legacy tool protection format (pre-authorization field)\n * Used during migration period to support both old and new formats\n */\nexport type LegacyToolProtection = Omit<ToolProtection, 'authorization'> & {\n oauthProvider?: string;\n};\n\n/**\n * Union type for both legacy and new formats\n * Useful during migration period when accepting tool protection input\n */\nexport type ToolProtectionInput = ToolProtection | LegacyToolProtection;\n\n/**\n * Zod Schemas for Validation\n */\n\nexport const AuthorizationRequirementSchema = z.discriminatedUnion('type', [\n // Deprecated: 'oauth' is an alias for 'oauth2'\n // Will be removed in v2.0.0. Use 'oauth2' instead.\n z.object({\n type: z.literal('oauth'),\n provider: z.string(),\n requiredScopes: z.array(z.string()).optional(),\n }),\n // OAuth 2.0 provider authentication (canonical)\n z.object({\n type: z.literal('oauth2'),\n provider: z.string(),\n requiredScopes: z.array(z.string()).optional(),\n }),\n z.object({\n type: z.literal('password'),\n provider: z.string(),\n }),\n z.object({\n type: z.literal('mdl'),\n issuer: z.string(),\n credentialType: z.string().optional(),\n }),\n z.object({\n type: z.literal('idv'),\n provider: z.string(),\n verificationLevel: z.enum(['basic', 'enhanced', 'loa3']).optional(),\n }),\n z.object({\n type: z.literal('verifiable_credential'),\n credentialType: z.string(),\n issuer: z.string().optional(),\n }),\n // Deprecated: 'credential' is an alias for 'verifiable_credential'\n // Will be removed in v2.0.0. Use 'verifiable_credential' instead.\n z.object({\n type: z.literal('credential'),\n credentialType: z.string(),\n issuer: z.string().optional(),\n }),\n // WebAuthn/Passkey authentication\n z.object({\n type: z.literal('webauthn'),\n rpId: z.string().optional(),\n userVerification: z.enum(['required', 'preferred', 'discouraged']).optional(),\n }),\n // Sign-In with Ethereum (EIP-4361)\n z.object({\n type: z.literal('siwe'),\n chainId: z.number().optional(),\n domain: z.string().optional(),\n }),\n // API Key from per-user vault\n z.object({\n type: z.literal('apikey'),\n envVarNames: z.array(envVarNameSchema).min(1),\n headerMapping: z.record(z.string(), z.string()),\n }),\n z.object({\n type: z.literal('none'),\n }),\n]);\n\nexport const ToolProtectionSchema = z.object({\n requiresDelegation: z.boolean(),\n requiredScopes: z.array(z.string()),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n oauthProvider: z.string().optional(), // Phase 2: Tool-specific OAuth provider\n authorization: AuthorizationRequirementSchema.optional(),\n});\n\nexport const ToolProtectionMapSchema = z.record(z.string(), ToolProtectionSchema);\n\nexport const ToolProtectionResponseSchema = z.object({\n toolProtections: ToolProtectionMapSchema,\n metadata: z\n .object({\n lastUpdated: z.string().optional(),\n version: z.string().optional(),\n source: z.string().optional(),\n })\n .optional(),\n});\n\nexport const DelegationRequiredErrorDataSchema = z.object({\n toolName: z.string(),\n requiredScopes: z.array(z.string()),\n consentUrl: z.string().optional(),\n authorizationUrl: z.string().optional(),\n reason: z.string().optional(),\n});\n\n/**\n * Type Guards\n */\n\nexport function isToolProtection(obj: unknown): obj is ToolProtection {\n return ToolProtectionSchema.safeParse(obj).success;\n}\n\nexport function isToolProtectionMap(obj: unknown): obj is ToolProtectionMap {\n return ToolProtectionMapSchema.safeParse(obj).success;\n}\n\nexport function isToolProtectionResponse(obj: unknown): obj is ToolProtectionResponse {\n return ToolProtectionResponseSchema.safeParse(obj).success;\n}\n\nexport function isDelegationRequiredErrorData(obj: unknown): obj is DelegationRequiredErrorData {\n return DelegationRequiredErrorDataSchema.safeParse(obj).success;\n}\n\n/**\n * Type guard to check if an object is a valid AuthorizationRequirement\n */\nexport function isAuthorizationRequirement(obj: unknown): obj is AuthorizationRequirement {\n return AuthorizationRequirementSchema.safeParse(obj).success;\n}\n\n/**\n * Type guard to check if a ToolProtection has OAuth authorization\n * Checks for both 'oauth' (deprecated) and 'oauth2' (canonical)\n */\nexport function hasOAuthAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'oauth' | 'oauth2' } } {\n return protection.authorization?.type === 'oauth' || protection.authorization?.type === 'oauth2';\n}\n\n/**\n * Type guard to check if a ToolProtection has password authorization\n */\nexport function hasPasswordAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'password' } } {\n return protection.authorization?.type === 'password';\n}\n\n/**\n * Type guard to check if a ToolProtection requires a Verifiable Credential\n *\n * Note: Also returns true for deprecated 'credential' type (normalized to verifiable_credential)\n */\nexport function hasVerifiableCredentialAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & {\n authorization: { type: 'verifiable_credential' | 'credential' };\n} {\n return (\n protection.authorization?.type === 'verifiable_credential' ||\n protection.authorization?.type === 'credential'\n );\n}\n\n/**\n * Type guard to check if a ToolProtection has API Key (vault) authorization\n */\nexport function hasApiKeyAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'apikey' } } {\n return protection.authorization?.type === 'apikey';\n}\n\n/**\n * Validation Functions\n */\n\nexport function validateToolProtection(obj: unknown): ToolProtection {\n return ToolProtectionSchema.parse(obj);\n}\n\nexport function validateToolProtectionMap(obj: unknown): ToolProtectionMap {\n return ToolProtectionMapSchema.parse(obj);\n}\n\nexport function validateToolProtectionResponse(obj: unknown): ToolProtectionResponse {\n return ToolProtectionResponseSchema.parse(obj);\n}\n\nexport function validateDelegationRequiredErrorData(obj: unknown): DelegationRequiredErrorData {\n return DelegationRequiredErrorDataSchema.parse(obj);\n}\n\n/**\n * Utility Functions\n */\n\n/**\n * Check if a tool requires delegation\n */\nexport function toolRequiresDelegation(toolName: string, protections: ToolProtectionMap): boolean {\n const protection = protections[toolName];\n return protection?.requiresDelegation ?? false;\n}\n\n/**\n * Get required scopes for a tool\n */\nexport function getToolRequiredScopes(toolName: string, protections: ToolProtectionMap): string[] {\n const protection = protections[toolName];\n return protection?.requiredScopes ?? [];\n}\n\n/**\n * Get risk level for a tool\n */\nexport function getToolRiskLevel(\n toolName: string,\n protections: ToolProtectionMap\n): ToolProtection['riskLevel'] | undefined {\n return protections[toolName]?.riskLevel;\n}\n\n/**\n * Create a delegation required error\n */\nexport function createDelegationRequiredError(\n toolName: string,\n requiredScopes: string[],\n consentUrl?: string\n): DelegationRequiredErrorData {\n return {\n toolName,\n requiredScopes,\n consentUrl,\n authorizationUrl: consentUrl, // Include both for compatibility\n };\n}\n\n/**\n * Normalize tool protection configuration\n * Migrates legacy oauthProvider field to authorization object\n *\n * - Migrates `oauthProvider` → `authorization: { type: 'oauth', provider: ... }`\n * - Ensures `authorization` field is present when `requiresDelegation=true`\n * - Returns fully normalized ToolProtection object\n *\n * @param raw - Raw tool protection data (may have legacy fields or be partial)\n * @returns Normalized ToolProtection object\n *\n * // TODO: Remove normalizeToolProtection() when all tools migrated\n */\nexport function normalizeToolProtection(\n raw: ToolProtection | PartialToolProtection\n): ToolProtection {\n // Ensure we have required fields (provide defaults for partial input)\n const normalized: ToolProtection = {\n requiresDelegation: raw.requiresDelegation ?? false,\n requiredScopes: raw.requiredScopes ?? [],\n ...(raw.riskLevel && { riskLevel: raw.riskLevel }),\n ...(raw.oauthProvider && { oauthProvider: raw.oauthProvider }),\n };\n\n // If authorization is already present, use it\n if (raw.authorization) {\n normalized.authorization = raw.authorization;\n return normalized;\n }\n\n // Migrate oauthProvider to authorization\n if (raw.oauthProvider) {\n normalized.authorization = {\n type: 'oauth',\n provider: raw.oauthProvider,\n };\n // Keep oauthProvider for backward compatibility\n return normalized;\n }\n\n // Default for requiresDelegation=true without specific auth: type='none' (consent only)\n // But ONLY if authorization is missing entirely\n if (normalized.requiresDelegation && !normalized.authorization && !normalized.oauthProvider) {\n // We don't automatically set type='none' here to allow\n // ProviderResolver to do its scope inference fallback logic.\n // The fallback logic will eventually be moved into an AuthorizationService.\n return normalized;\n }\n\n return normalized;\n}\n\n// =============================================================================\n// CONSENT PROVIDER TYPES - Records what auth method was USED (not required)\n// =============================================================================\n\n/** Consent provider types - stored in delegation metadata to track auth method used */\nexport const CONSENT_PROVIDER_TYPES = {\n /** Consent-only mode - no authentication, just clickwrap agreement */\n NONE: 'none',\n /** OAuth2 provider authentication */\n OAUTH2: 'oauth2',\n /** Password-based authentication (email/password, username/password) */\n PASSWORD: 'password',\n /** @deprecated Use PASSWORD instead. Alias for backward compatibility */\n CREDENTIAL: 'credential',\n /** Email magic link authentication */\n MAGIC_LINK: 'magic_link',\n /** One-time password (SMS/email code) */\n OTP: 'otp',\n} as const;\n\nexport type ConsentProviderType =\n (typeof CONSENT_PROVIDER_TYPES)[keyof typeof CONSENT_PROVIDER_TYPES];\n\n/**\n * Determine consent provider type based on available identity information\n *\n * This is the single source of truth for consent provider type determination.\n *\n * @param hasOAuthIdentity - Whether OAuth identity is available\n * @param isPasswordFlow - Whether this is a password/credential flow\n * @param isMagicLinkFlow - Whether this is a magic link flow\n * @param isOtpFlow - Whether this is an OTP flow\n * @returns The consent provider type\n */\nexport function determineConsentProviderType(\n hasOAuthIdentity: boolean,\n isPasswordFlow: boolean = false,\n isMagicLinkFlow: boolean = false,\n isOtpFlow: boolean = false\n): ConsentProviderType {\n if (isPasswordFlow) {\n return CONSENT_PROVIDER_TYPES.PASSWORD;\n }\n if (isMagicLinkFlow) {\n return CONSENT_PROVIDER_TYPES.MAGIC_LINK;\n }\n if (isOtpFlow) {\n return CONSENT_PROVIDER_TYPES.OTP;\n }\n if (hasOAuthIdentity) {\n return CONSENT_PROVIDER_TYPES.OAUTH2;\n }\n return CONSENT_PROVIDER_TYPES.NONE;\n}\n\n/**\n * Get a human-readable label for an authorization requirement type\n */\nexport function getAuthorizationTypeLabel(auth: AuthorizationRequirement): string {\n switch (auth.type) {\n case 'oauth':\n case 'oauth2':\n return auth.provider\n ? auth.provider.charAt(0).toUpperCase() + auth.provider.slice(1)\n : 'OAuth Provider';\n case 'password':\n return 'Password Authentication';\n case 'mdl':\n return \"Mobile Driver's License\";\n case 'idv':\n return 'Identity Verification';\n case 'verifiable_credential':\n return auth.credentialType || 'Verifiable Credential';\n case 'credential':\n // Deprecated: treat as verifiable_credential\n return auth.credentialType || 'Verifiable Credential';\n case 'webauthn':\n return 'Passkey / WebAuthn';\n case 'siwe':\n return 'Sign-In with Ethereum';\n case 'apikey':\n return 'API Key (Vault)';\n case 'none':\n return 'Consent Only';\n default: {\n // Closed union — this default is unreachable for well-typed input.\n return 'Unknown';\n }\n }\n}\n\n/**\n * Get a unique key for an authorization requirement (for React keys, caching, etc.)\n */\nexport function getAuthorizationTypeKey(auth: AuthorizationRequirement): string {\n switch (auth.type) {\n case 'oauth':\n // Keep original key format for backward compatibility with existing cache entries\n // Handle undefined provider gracefully (may come from loose API response types)\n return auth.provider ? `oauth:${auth.provider}` : 'oauth';\n case 'oauth2':\n return auth.provider ? `oauth2:${auth.provider}` : 'oauth2';\n case 'password':\n return auth.provider ? `password:${auth.provider}` : 'password';\n case 'mdl':\n // Keep trailing colon for backward compatibility with existing cache entries\n return `mdl:${auth.issuer || 'unknown'}:${auth.credentialType || ''}`;\n case 'idv':\n // Keep trailing colon for backward compatibility with existing cache entries\n return `idv:${auth.provider || 'unknown'}:${auth.verificationLevel || ''}`;\n case 'verifiable_credential':\n return `vc:${auth.issuer || 'any'}:${auth.credentialType || 'unknown'}`;\n case 'credential':\n // Deprecated: treat as verifiable_credential\n return `vc:${auth.issuer || 'any'}:${auth.credentialType || 'unknown'}`;\n case 'webauthn':\n return `webauthn:${auth.rpId || 'default'}`;\n case 'siwe':\n return `siwe:${auth.chainId || 1}:${auth.domain || 'any'}`;\n case 'apikey':\n return `apikey:${[...auth.envVarNames].sort().join(',')}`;\n case 'none':\n return 'none';\n default: {\n // Closed union — this default is unreachable for well-typed input.\n return 'unknown';\n }\n }\n}\n\n/**\n * Normalize authorization requirement type\n *\n * Normalizes deprecated types to their canonical equivalents:\n * - 'oauth' → 'oauth2'\n * - 'credential' → 'verifiable_credential'\n *\n * This function should be called at runtime boundaries when processing\n * authorization requirements.\n *\n * @param auth - Authorization requirement (may contain deprecated types)\n * @param options - Normalization options\n * @returns Normalized authorization requirement\n *\n * @example\n * ```typescript\n * const normalized = normalizeAuthorizationType(\n * { type: 'oauth', provider: 'github' },\n * { warn: true }\n * );\n * // Returns: { type: 'oauth2', provider: 'github' }\n * // Logs: DEPRECATION warning\n * ```\n */\nexport function normalizeAuthorizationType(\n auth: AuthorizationRequirement,\n options: { warn?: boolean; logger?: (message: string) => void } = {}\n): AuthorizationRequirement {\n const { warn = true, logger = console.warn } = options;\n\n // Normalize 'oauth' to 'oauth2'\n if (auth.type === 'oauth') {\n if (warn) {\n logger(\n `DEPRECATION: Authorization type 'oauth' is deprecated and will be removed in v2.0.0. ` +\n `Please update to 'oauth2'. ` +\n `See https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/docs/migrations/oauth-to-oauth2.md`\n );\n }\n\n // Normalize to oauth2\n const normalized = {\n type: 'oauth2' as const,\n provider: auth.provider,\n ...(auth.requiredScopes !== undefined && { requiredScopes: auth.requiredScopes }),\n };\n\n return normalized;\n }\n\n // Normalize 'credential' to 'verifiable_credential'\n if (auth.type === 'credential') {\n if (warn) {\n logger(\n `DEPRECATION: Authorization type 'credential' is deprecated and will be removed in v2.0.0. ` +\n `Please update to 'verifiable_credential'. ` +\n `See https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/docs/migrations/credential-to-verifiable_credential.md`\n );\n }\n\n // Normalize to verifiable_credential\n const normalized = {\n type: 'verifiable_credential' as const,\n credentialType: auth.credentialType,\n ...(auth.issuer !== undefined && { issuer: auth.issuer }),\n };\n\n return normalized;\n }\n\n // No normalization needed\n return auth;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,mBAAmB,EACtB,OAAO,CAAC,CACR,MAAM,qBAAiB,gDAAgD,CAAC,CACxE,IAAI,GAAG;;AA2EV,MAAa,sBAAsB;;CAEjC,OAAO;;CAEP,QAAQ;CACR,UAAU;CACV,KAAK;CACL,KAAK;CACL,uBAAuB;;CAEvB,UAAU;;CAEV,MAAM;;CAEN,QAAQ;CACR,MAAM;AACR;AAoKA,MAAa,8BAA8B,EAAE,OAAO;CAClD,OAAO,EAAE,QAAQ,eAAe;CAChC,MAAM,EAAE,KAAK;EAAC;EAAU;EAAS;CAAY,CAAC;CAC9C,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CAC1C,WAAW,EAAE,OAAO;CACpB,SAAS,EAAE,OAAO;AACpB,CAAC;;;;;;;AAQD,IAAa,oBAAb,cAAuC,MAAM;CAC3C,AAAgB;CAChB,AAAgB;CAChB,AAAgB;CAEhB,YAAY,MAKT;EACD,MAAM,UACJ,KAAK,YACJ,KAAK,SAAS,YAAY,KAAK,aAAa,SACzC,+BAA+B,KAAK,YAAY,KAAK,IAAI,EAAE,8BAC3D;EACN,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO,KAAK;EACjB,KAAK,cAAc,KAAK;EACxB,KAAK,YAAY,KAAK;CACxB;;CAGA,SA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ClB;CAGA,IAAI,KAAK,SAAS,cAAc;EAC9B,IAAI,MACF,OACE,kQAGF;EAUF,OAAO;GALL,MAAM;GACN,gBAAgB,KAAK;GACrB,GAAI,KAAK,WAAW,UAAa,EAAE,QAAQ,KAAK,OAAO;EAGzC;CAClB;CAGA,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/tool-protection/default-required-scopes.ts","../../src/tool-protection/index.ts"],"sourcesContent":["/**\n * The scopes a tool entry is served with when it has none of its own.\n *\n * The edge and the runtime let a credential through a protected tool when it\n * carries every scope in the tool's served `requiredScopes`, so a protected\n * tool served with `[]` opens to ANY valid credential for the resource. Every\n * writer of `bouncer_configs.discovered_tools` stores a scope through this one\n * rule, so a tool never reaches the served map with an empty list.\n *\n * @module @kya-os/checkpoint-shared/tool-protection\n */\n\n/** The fields of a stored tool entry this rule reads. Stored rows are untyped JSON. */\nexport interface ToolScopeSources {\n /** The entry's own served scopes. */\n requiredScopes?: unknown;\n /** The legacy key proof discovery wrote: the scope the runtime reported (`scopeId`). */\n scopes?: unknown;\n /** The security schemes a server declared for the tool; oauth2 entries carry `scopes`. */\n securitySchemes?: unknown;\n /** The capability the tool gates on, from server registration. */\n capability?: unknown;\n}\n\n/** The longest scope a consent request carries. */\nexport const MAX_DEFAULT_SCOPE_LENGTH = 200;\n\nconst EXECUTE_SUFFIX = ':execute';\n\n/** Outside the RFC 6749 scope-token alphabet: printable ASCII except space, `\"` and `\\`. */\nconst NON_SCOPE_TOKEN_CHARS = /[^\\x21\\x23-\\x5B\\x5D-\\x7E]/gu;\n\nfunction scopeList(value: unknown): string[] | undefined {\n return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'string')\n ? value\n : undefined;\n}\n\nfunction declaredOauthScopes(schemes: unknown): string[] {\n if (!Array.isArray(schemes)) return [];\n const scopes = schemes.flatMap((scheme: unknown) =>\n typeof scheme === 'object' &&\n scheme !== null &&\n (scheme as { type?: unknown }).type === 'oauth2' &&\n Array.isArray((scheme as { scopes?: unknown }).scopes)\n ? ((scheme as { scopes: unknown[] }).scopes.filter(\n (scope) => typeof scope === 'string' && scope.length > 0\n ) as string[])\n : []\n );\n return [...new Set(scopes)];\n}\n\n/**\n * `<name>:execute`, with the name reduced to the scope-token alphabet (the edge\n * drops other characters) and the whole scope at most\n * {@link MAX_DEFAULT_SCOPE_LENGTH} characters.\n */\nexport function executeScopeFor(toolName: string): string {\n const name = toolName\n .replace(NON_SCOPE_TOKEN_CHARS, '_')\n .slice(0, MAX_DEFAULT_SCOPE_LENGTH - EXECUTE_SUFFIX.length);\n return `${name}${EXECUTE_SUFFIX}`;\n}\n\n/**\n * The scopes to store for `toolName`: the first non-empty of\n *\n * 1. the entry's own `requiredScopes`, as stored;\n * 2. its legacy `scopes`, so a grant for the scope the runtime reported keeps matching;\n * 3. the oauth2 scopes its `securitySchemes` declare;\n * 4. its `capability`;\n * 5. {@link executeScopeFor}`(toolName)`.\n *\n * Never empty. An absent entry gets the last.\n */\nexport function defaultRequiredScopes(\n toolName: string,\n entry: ToolScopeSources | null | undefined\n): string[] {\n const own = scopeList(entry?.requiredScopes) ?? scopeList(entry?.scopes);\n if (own) return [...own];\n const declared = declaredOauthScopes(entry?.securitySchemes);\n if (declared.length > 0) return declared;\n if (typeof entry?.capability === 'string' && entry.capability.length > 0) {\n return [entry.capability];\n }\n return [executeScopeFor(toolName)];\n}\n","/**\n * KYA-OS Tool Protection Specification\n *\n * Core types for tool protection with delegation requirements.\n *\n * Consent Flow: type='none' → 2 screens, others → 3 screens (Auth→Consent→Success).\n * DelegationCredential (VC) is created when user confirms on Consent Screen.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/tool-protection` as part\n * of the E6 / C-series decommission (#2914 / #2917): checkpoint owns its product\n * types now that the DIF `@kya-os/mcp` core is protocol-only. The single external\n * dependency (`envVarNameSchema` from the contracts `vault` module) is inlined\n * below so this module pulls nothing from `@kya-os/contracts`.\n *\n * @module @kya-os/checkpoint-shared/tool-protection\n */\n\nimport { z } from 'zod';\n\nexport {\n defaultRequiredScopes,\n executeScopeFor,\n MAX_DEFAULT_SCOPE_LENGTH,\n type ToolScopeSources,\n} from './default-required-scopes';\n\n/**\n * Pattern for valid environment variable names (e.g., X_API_KEY, OPENAI_KEY).\n * Inlined from the former `@kya-os/contracts/vault` `ENV_VAR_PATTERN`.\n */\nconst ENV_VAR_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\n/**\n * Validates an env var name used by the `apikey` authorization requirement.\n * Inlined from the former `@kya-os/contracts/vault` `envVarNameSchema`.\n */\nconst envVarNameSchema = z\n .string()\n .regex(ENV_VAR_PATTERN, 'Must be a valid env var name (e.g., X_API_KEY)')\n .max(255);\n\n/**\n * Authorization Requirement - what auth is needed BEFORE consent screen.\n *\n * Types: none (2 screens), oauth/password/mdl/idv (3 screens), verifiable_credential (future).\n * The VC output is always a DelegationCredential created on consent confirmation.\n */\nexport type AuthorizationRequirement =\n | {\n /**\n * @deprecated Use 'oauth2' instead. Will be removed in v2.0.0.\n */\n type: 'oauth';\n provider: string; // \"github\", \"google\", etc.\n requiredScopes?: string[]; // Provider-specific scopes\n }\n | {\n /** OAuth 2.0 provider authentication (canonical) */\n type: 'oauth2';\n provider: string; // \"github\", \"google\", etc.\n requiredScopes?: string[]; // Provider-specific scopes\n }\n | {\n type: 'password';\n provider: string; // Credential provider ID (e.g., \"hardwareworld\", \"custom\")\n }\n | {\n type: 'mdl';\n issuer: string; // MDL issuer DID or identifier\n credentialType?: string; // Specific MDL credential type\n }\n | {\n type: 'idv';\n provider: string; // IDV provider name\n verificationLevel?: 'basic' | 'enhanced' | 'loa3';\n }\n | {\n /** Require user to present an existing VC */\n type: 'verifiable_credential';\n credentialType: string;\n issuer?: string;\n }\n | {\n /**\n * @deprecated Use 'verifiable_credential' instead. Will be removed in v2.0.0.\n * This is an alias for 'verifiable_credential' for backward compatibility.\n */\n type: 'credential';\n credentialType: string;\n issuer?: string;\n }\n | {\n /** WebAuthn/Passkey authentication */\n type: 'webauthn';\n rpId?: string; // Relying Party ID\n userVerification?: 'required' | 'preferred' | 'discouraged';\n }\n | {\n /** Sign-In with Ethereum (EIP-4361) */\n type: 'siwe';\n chainId?: number; // Ethereum chain ID (1 = mainnet, 137 = polygon, etc.)\n domain?: string; // Domain for SIWE message\n }\n | {\n /** API Key from per-user vault */\n type: 'apikey';\n envVarNames: string[]; // Env var names to resolve from vault (e.g., ['X_API_KEY'])\n headerMapping: Record<string, string>; // Map env var → HTTP header (e.g., { X_API_KEY: 'X-API-Key' })\n }\n | {\n type: 'none'; // Just consent checkbox, no external auth\n };\n\n/** Canonical authorization type values for type safety */\nexport const AUTHORIZATION_TYPES = {\n /** @deprecated Use OAUTH2 instead. Will be removed in v2.0.0. */\n OAUTH: 'oauth',\n /** OAuth 2.0 provider authentication (canonical) */\n OAUTH2: 'oauth2',\n PASSWORD: 'password',\n MDL: 'mdl',\n IDV: 'idv',\n VERIFIABLE_CREDENTIAL: 'verifiable_credential',\n /** WebAuthn/Passkey authentication */\n WEBAUTHN: 'webauthn',\n /** Sign-In with Ethereum (EIP-4361) */\n SIWE: 'siwe',\n /** API Key from per-user vault */\n APIKEY: 'apikey',\n NONE: 'none',\n} as const;\n\nexport type AuthorizationType = (typeof AUTHORIZATION_TYPES)[keyof typeof AUTHORIZATION_TYPES];\n\n/**\n * Tool Protection Definition\n *\n * Defines the protection requirements for a tool as per KYA-OS spec.\n * This is the canonical definition that all implementations must follow.\n */\nexport interface ToolProtection {\n /**\n * Whether this tool requires explicit delegation from the user\n */\n requiresDelegation: boolean;\n\n /**\n * The scopes required to execute this tool\n * Format: \"resource:action\" (e.g., \"files:read\", \"payment:send\")\n */\n requiredScopes: string[];\n\n /**\n * Risk level classification for the tool\n * Used to determine appropriate authorization flows\n */\n riskLevel?: 'low' | 'medium' | 'high' | 'critical';\n\n /**\n * OAuth provider name for this tool (Phase 2+)\n * If specified, this tool will use the specified OAuth provider.\n * If not specified, provider will be resolved via fallback strategies.\n * @example \"github\", \"google\", \"microsoft\"\n * @deprecated Use `authorization` field instead. Will be removed in Phase 3.\n */\n oauthProvider?: string;\n\n /**\n * Authorization requirement for this tool\n * If requiresDelegation=true, authorization must be specified (or inferred from legacy fields)\n */\n authorization?: AuthorizationRequirement;\n}\n\n/**\n * Tool Protection Map\n *\n * A mapping of tool names to their protection configurations.\n * This is how tool protections are typically stored and transmitted.\n */\nexport type ToolProtectionMap = Record<string, ToolProtection>;\n\n/**\n * Partial tool protection for updates (all fields optional)\n * Use this when accepting partial updates to tool protection settings\n */\nexport type PartialToolProtection = Partial<ToolProtection>;\n\n/**\n * Tool protection with explicit optional fields\n * Useful when TypeScript's Partial<T> doesn't preserve optional property access\n * Supports explicit null values to clear fields\n */\nexport type ToolProtectionUpdate = {\n requiresDelegation?: boolean;\n requiredScopes?: string[];\n riskLevel?: 'low' | 'medium' | 'high' | 'critical';\n oauthProvider?: string | null; // null explicitly clears the field\n authorization?: AuthorizationRequirement | null; // null explicitly clears the field\n};\n\n/**\n * Tool Protection Response\n *\n * The response format when querying for tool protections.\n * Used by tool protection services and APIs.\n */\nexport interface ToolProtectionResponse {\n /**\n * The tool protections keyed by tool name\n */\n toolProtections: ToolProtectionMap;\n\n /**\n * Optional metadata about the response\n */\n metadata?: {\n /**\n * When this configuration was last updated\n */\n lastUpdated?: string;\n\n /**\n * Version of the configuration\n */\n version?: string;\n\n /**\n * Source of the configuration\n */\n source?: string;\n };\n}\n\n/**\n * Delegation Required Error Data\n *\n * The standardized error data returned when a tool requires delegation\n * but none was provided. This is part of the KYA-OS error protocol.\n */\nexport interface DelegationRequiredErrorData {\n /**\n * The name of the tool that requires delegation\n */\n toolName: string;\n\n /**\n * The scopes required for this tool\n */\n requiredScopes: string[];\n\n /**\n * URL where the user can provide consent/delegation\n */\n consentUrl?: string;\n\n /**\n * Alternative field for consent URL (for compatibility)\n */\n authorizationUrl?: string;\n\n /**\n * Additional context about why delegation is required\n */\n reason?: string;\n}\n\n/**\n * Auth Required Error Data\n *\n * Machine-readable error returned when a tool requires per-user auth\n * (vault secret, OAuth, credential) but none is configured and no\n * static env fallback exists. MCP clients use this to present\n * actionable guidance (e.g., \"Add your PulseMCP API key\" with a link).\n *\n * Closes VAULT-11\n */\nexport interface AuthRequiredErrorData {\n /** Discriminator — always \"auth_required\" */\n error: 'auth_required';\n\n /** Which auth mechanism is missing */\n type: 'apikey' | 'oauth' | 'credential';\n\n /** For apikey: which env vars are missing */\n envVarNames?: string[];\n\n /** Dashboard URL where the user can configure the missing auth */\n configUrl: string;\n\n /** Human-readable fallback message */\n message: string;\n}\n\nexport const AuthRequiredErrorDataSchema = z.object({\n error: z.literal('auth_required'),\n type: z.enum(['apikey', 'oauth', 'credential']),\n envVarNames: z.array(z.string()).optional(),\n configUrl: z.string(),\n message: z.string(),\n});\n\n/**\n * Error class thrown when required auth is missing and no fallback exists.\n *\n * Caught by the tool-call handler in agent.ts and serialized as a\n * machine-readable MCP tool result so clients can present actionable UI.\n */\nexport class AuthRequiredError extends Error {\n public readonly type: AuthRequiredErrorData['type'];\n public readonly envVarNames?: string[];\n public readonly configUrl: string;\n\n constructor(opts: {\n type: AuthRequiredErrorData['type'];\n envVarNames?: string[];\n configUrl: string;\n message?: string;\n }) {\n const message =\n opts.message ??\n (opts.type === 'apikey' && opts.envVarNames?.length\n ? `API key required: configure ${opts.envVarNames.join(', ')} in your project settings.`\n : 'Authentication required to use this tool.');\n super(message);\n this.name = 'AuthRequiredError';\n this.type = opts.type;\n this.envVarNames = opts.envVarNames;\n this.configUrl = opts.configUrl;\n }\n\n /** Serialize to the wire format MCP clients expect */\n toJSON(): AuthRequiredErrorData {\n return {\n error: 'auth_required',\n type: this.type,\n ...(this.envVarNames && { envVarNames: this.envVarNames }),\n configUrl: this.configUrl,\n message: this.message,\n };\n }\n}\n\n/**\n * Legacy tool protection format (pre-authorization field)\n * Used during migration period to support both old and new formats\n */\nexport type LegacyToolProtection = Omit<ToolProtection, 'authorization'> & {\n oauthProvider?: string;\n};\n\n/**\n * Union type for both legacy and new formats\n * Useful during migration period when accepting tool protection input\n */\nexport type ToolProtectionInput = ToolProtection | LegacyToolProtection;\n\n/**\n * Zod Schemas for Validation\n */\n\nexport const AuthorizationRequirementSchema = z.discriminatedUnion('type', [\n // Deprecated: 'oauth' is an alias for 'oauth2'\n // Will be removed in v2.0.0. Use 'oauth2' instead.\n z.object({\n type: z.literal('oauth'),\n provider: z.string(),\n requiredScopes: z.array(z.string()).optional(),\n }),\n // OAuth 2.0 provider authentication (canonical)\n z.object({\n type: z.literal('oauth2'),\n provider: z.string(),\n requiredScopes: z.array(z.string()).optional(),\n }),\n z.object({\n type: z.literal('password'),\n provider: z.string(),\n }),\n z.object({\n type: z.literal('mdl'),\n issuer: z.string(),\n credentialType: z.string().optional(),\n }),\n z.object({\n type: z.literal('idv'),\n provider: z.string(),\n verificationLevel: z.enum(['basic', 'enhanced', 'loa3']).optional(),\n }),\n z.object({\n type: z.literal('verifiable_credential'),\n credentialType: z.string(),\n issuer: z.string().optional(),\n }),\n // Deprecated: 'credential' is an alias for 'verifiable_credential'\n // Will be removed in v2.0.0. Use 'verifiable_credential' instead.\n z.object({\n type: z.literal('credential'),\n credentialType: z.string(),\n issuer: z.string().optional(),\n }),\n // WebAuthn/Passkey authentication\n z.object({\n type: z.literal('webauthn'),\n rpId: z.string().optional(),\n userVerification: z.enum(['required', 'preferred', 'discouraged']).optional(),\n }),\n // Sign-In with Ethereum (EIP-4361)\n z.object({\n type: z.literal('siwe'),\n chainId: z.number().optional(),\n domain: z.string().optional(),\n }),\n // API Key from per-user vault\n z.object({\n type: z.literal('apikey'),\n envVarNames: z.array(envVarNameSchema).min(1),\n headerMapping: z.record(z.string(), z.string()),\n }),\n z.object({\n type: z.literal('none'),\n }),\n]);\n\nexport const ToolProtectionSchema = z.object({\n requiresDelegation: z.boolean(),\n requiredScopes: z.array(z.string()),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n oauthProvider: z.string().optional(), // Phase 2: Tool-specific OAuth provider\n authorization: AuthorizationRequirementSchema.optional(),\n});\n\nexport const ToolProtectionMapSchema = z.record(z.string(), ToolProtectionSchema);\n\nexport const ToolProtectionResponseSchema = z.object({\n toolProtections: ToolProtectionMapSchema,\n metadata: z\n .object({\n lastUpdated: z.string().optional(),\n version: z.string().optional(),\n source: z.string().optional(),\n })\n .optional(),\n});\n\nexport const DelegationRequiredErrorDataSchema = z.object({\n toolName: z.string(),\n requiredScopes: z.array(z.string()),\n consentUrl: z.string().optional(),\n authorizationUrl: z.string().optional(),\n reason: z.string().optional(),\n});\n\n/**\n * Type Guards\n */\n\nexport function isToolProtection(obj: unknown): obj is ToolProtection {\n return ToolProtectionSchema.safeParse(obj).success;\n}\n\nexport function isToolProtectionMap(obj: unknown): obj is ToolProtectionMap {\n return ToolProtectionMapSchema.safeParse(obj).success;\n}\n\nexport function isToolProtectionResponse(obj: unknown): obj is ToolProtectionResponse {\n return ToolProtectionResponseSchema.safeParse(obj).success;\n}\n\nexport function isDelegationRequiredErrorData(obj: unknown): obj is DelegationRequiredErrorData {\n return DelegationRequiredErrorDataSchema.safeParse(obj).success;\n}\n\n/**\n * Type guard to check if an object is a valid AuthorizationRequirement\n */\nexport function isAuthorizationRequirement(obj: unknown): obj is AuthorizationRequirement {\n return AuthorizationRequirementSchema.safeParse(obj).success;\n}\n\n/**\n * Type guard to check if a ToolProtection has OAuth authorization\n * Checks for both 'oauth' (deprecated) and 'oauth2' (canonical)\n */\nexport function hasOAuthAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'oauth' | 'oauth2' } } {\n return protection.authorization?.type === 'oauth' || protection.authorization?.type === 'oauth2';\n}\n\n/**\n * Type guard to check if a ToolProtection has password authorization\n */\nexport function hasPasswordAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'password' } } {\n return protection.authorization?.type === 'password';\n}\n\n/**\n * Type guard to check if a ToolProtection requires a Verifiable Credential\n *\n * Note: Also returns true for deprecated 'credential' type (normalized to verifiable_credential)\n */\nexport function hasVerifiableCredentialAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & {\n authorization: { type: 'verifiable_credential' | 'credential' };\n} {\n return (\n protection.authorization?.type === 'verifiable_credential' ||\n protection.authorization?.type === 'credential'\n );\n}\n\n/**\n * Type guard to check if a ToolProtection has API Key (vault) authorization\n */\nexport function hasApiKeyAuthorization(\n protection: ToolProtection\n): protection is ToolProtection & { authorization: { type: 'apikey' } } {\n return protection.authorization?.type === 'apikey';\n}\n\n/**\n * Validation Functions\n */\n\nexport function validateToolProtection(obj: unknown): ToolProtection {\n return ToolProtectionSchema.parse(obj);\n}\n\nexport function validateToolProtectionMap(obj: unknown): ToolProtectionMap {\n return ToolProtectionMapSchema.parse(obj);\n}\n\nexport function validateToolProtectionResponse(obj: unknown): ToolProtectionResponse {\n return ToolProtectionResponseSchema.parse(obj);\n}\n\nexport function validateDelegationRequiredErrorData(obj: unknown): DelegationRequiredErrorData {\n return DelegationRequiredErrorDataSchema.parse(obj);\n}\n\n/**\n * Utility Functions\n */\n\n/**\n * Check if a tool requires delegation\n */\nexport function toolRequiresDelegation(toolName: string, protections: ToolProtectionMap): boolean {\n const protection = protections[toolName];\n return protection?.requiresDelegation ?? false;\n}\n\n/**\n * Get required scopes for a tool\n */\nexport function getToolRequiredScopes(toolName: string, protections: ToolProtectionMap): string[] {\n const protection = protections[toolName];\n return protection?.requiredScopes ?? [];\n}\n\n/**\n * Get risk level for a tool\n */\nexport function getToolRiskLevel(\n toolName: string,\n protections: ToolProtectionMap\n): ToolProtection['riskLevel'] | undefined {\n return protections[toolName]?.riskLevel;\n}\n\n/**\n * Create a delegation required error\n */\nexport function createDelegationRequiredError(\n toolName: string,\n requiredScopes: string[],\n consentUrl?: string\n): DelegationRequiredErrorData {\n return {\n toolName,\n requiredScopes,\n consentUrl,\n authorizationUrl: consentUrl, // Include both for compatibility\n };\n}\n\n/**\n * Normalize tool protection configuration\n * Migrates legacy oauthProvider field to authorization object\n *\n * - Migrates `oauthProvider` → `authorization: { type: 'oauth', provider: ... }`\n * - Ensures `authorization` field is present when `requiresDelegation=true`\n * - Returns fully normalized ToolProtection object\n *\n * @param raw - Raw tool protection data (may have legacy fields or be partial)\n * @returns Normalized ToolProtection object\n *\n * // TODO: Remove normalizeToolProtection() when all tools migrated\n */\nexport function normalizeToolProtection(\n raw: ToolProtection | PartialToolProtection\n): ToolProtection {\n // Ensure we have required fields (provide defaults for partial input)\n const normalized: ToolProtection = {\n requiresDelegation: raw.requiresDelegation ?? false,\n requiredScopes: raw.requiredScopes ?? [],\n ...(raw.riskLevel && { riskLevel: raw.riskLevel }),\n ...(raw.oauthProvider && { oauthProvider: raw.oauthProvider }),\n };\n\n // If authorization is already present, use it\n if (raw.authorization) {\n normalized.authorization = raw.authorization;\n return normalized;\n }\n\n // Migrate oauthProvider to authorization\n if (raw.oauthProvider) {\n normalized.authorization = {\n type: 'oauth',\n provider: raw.oauthProvider,\n };\n // Keep oauthProvider for backward compatibility\n return normalized;\n }\n\n // Default for requiresDelegation=true without specific auth: type='none' (consent only)\n // But ONLY if authorization is missing entirely\n if (normalized.requiresDelegation && !normalized.authorization && !normalized.oauthProvider) {\n // We don't automatically set type='none' here to allow\n // ProviderResolver to do its scope inference fallback logic.\n // The fallback logic will eventually be moved into an AuthorizationService.\n return normalized;\n }\n\n return normalized;\n}\n\n// =============================================================================\n// CONSENT PROVIDER TYPES - Records what auth method was USED (not required)\n// =============================================================================\n\n/** Consent provider types - stored in delegation metadata to track auth method used */\nexport const CONSENT_PROVIDER_TYPES = {\n /** Consent-only mode - no authentication, just clickwrap agreement */\n NONE: 'none',\n /** OAuth2 provider authentication */\n OAUTH2: 'oauth2',\n /** Password-based authentication (email/password, username/password) */\n PASSWORD: 'password',\n /** @deprecated Use PASSWORD instead. Alias for backward compatibility */\n CREDENTIAL: 'credential',\n /** Email magic link authentication */\n MAGIC_LINK: 'magic_link',\n /** One-time password (SMS/email code) */\n OTP: 'otp',\n} as const;\n\nexport type ConsentProviderType =\n (typeof CONSENT_PROVIDER_TYPES)[keyof typeof CONSENT_PROVIDER_TYPES];\n\n/**\n * Determine consent provider type based on available identity information\n *\n * This is the single source of truth for consent provider type determination.\n *\n * @param hasOAuthIdentity - Whether OAuth identity is available\n * @param isPasswordFlow - Whether this is a password/credential flow\n * @param isMagicLinkFlow - Whether this is a magic link flow\n * @param isOtpFlow - Whether this is an OTP flow\n * @returns The consent provider type\n */\nexport function determineConsentProviderType(\n hasOAuthIdentity: boolean,\n isPasswordFlow: boolean = false,\n isMagicLinkFlow: boolean = false,\n isOtpFlow: boolean = false\n): ConsentProviderType {\n if (isPasswordFlow) {\n return CONSENT_PROVIDER_TYPES.PASSWORD;\n }\n if (isMagicLinkFlow) {\n return CONSENT_PROVIDER_TYPES.MAGIC_LINK;\n }\n if (isOtpFlow) {\n return CONSENT_PROVIDER_TYPES.OTP;\n }\n if (hasOAuthIdentity) {\n return CONSENT_PROVIDER_TYPES.OAUTH2;\n }\n return CONSENT_PROVIDER_TYPES.NONE;\n}\n\n/**\n * Get a human-readable label for an authorization requirement type\n */\nexport function getAuthorizationTypeLabel(auth: AuthorizationRequirement): string {\n switch (auth.type) {\n case 'oauth':\n case 'oauth2':\n return auth.provider\n ? auth.provider.charAt(0).toUpperCase() + auth.provider.slice(1)\n : 'OAuth Provider';\n case 'password':\n return 'Password Authentication';\n case 'mdl':\n return \"Mobile Driver's License\";\n case 'idv':\n return 'Identity Verification';\n case 'verifiable_credential':\n return auth.credentialType || 'Verifiable Credential';\n case 'credential':\n // Deprecated: treat as verifiable_credential\n return auth.credentialType || 'Verifiable Credential';\n case 'webauthn':\n return 'Passkey / WebAuthn';\n case 'siwe':\n return 'Sign-In with Ethereum';\n case 'apikey':\n return 'API Key (Vault)';\n case 'none':\n return 'Consent Only';\n default: {\n // Closed union — this default is unreachable for well-typed input.\n return 'Unknown';\n }\n }\n}\n\n/**\n * Get a unique key for an authorization requirement (for React keys, caching, etc.)\n */\nexport function getAuthorizationTypeKey(auth: AuthorizationRequirement): string {\n switch (auth.type) {\n case 'oauth':\n // Keep original key format for backward compatibility with existing cache entries\n // Handle undefined provider gracefully (may come from loose API response types)\n return auth.provider ? `oauth:${auth.provider}` : 'oauth';\n case 'oauth2':\n return auth.provider ? `oauth2:${auth.provider}` : 'oauth2';\n case 'password':\n return auth.provider ? `password:${auth.provider}` : 'password';\n case 'mdl':\n // Keep trailing colon for backward compatibility with existing cache entries\n return `mdl:${auth.issuer || 'unknown'}:${auth.credentialType || ''}`;\n case 'idv':\n // Keep trailing colon for backward compatibility with existing cache entries\n return `idv:${auth.provider || 'unknown'}:${auth.verificationLevel || ''}`;\n case 'verifiable_credential':\n return `vc:${auth.issuer || 'any'}:${auth.credentialType || 'unknown'}`;\n case 'credential':\n // Deprecated: treat as verifiable_credential\n return `vc:${auth.issuer || 'any'}:${auth.credentialType || 'unknown'}`;\n case 'webauthn':\n return `webauthn:${auth.rpId || 'default'}`;\n case 'siwe':\n return `siwe:${auth.chainId || 1}:${auth.domain || 'any'}`;\n case 'apikey':\n return `apikey:${[...auth.envVarNames].sort().join(',')}`;\n case 'none':\n return 'none';\n default: {\n // Closed union — this default is unreachable for well-typed input.\n return 'unknown';\n }\n }\n}\n\n/**\n * Normalize authorization requirement type\n *\n * Normalizes deprecated types to their canonical equivalents:\n * - 'oauth' → 'oauth2'\n * - 'credential' → 'verifiable_credential'\n *\n * This function should be called at runtime boundaries when processing\n * authorization requirements.\n *\n * @param auth - Authorization requirement (may contain deprecated types)\n * @param options - Normalization options\n * @returns Normalized authorization requirement\n *\n * @example\n * ```typescript\n * const normalized = normalizeAuthorizationType(\n * { type: 'oauth', provider: 'github' },\n * { warn: true }\n * );\n * // Returns: { type: 'oauth2', provider: 'github' }\n * // Logs: DEPRECATION warning\n * ```\n */\nexport function normalizeAuthorizationType(\n auth: AuthorizationRequirement,\n options: { warn?: boolean; logger?: (message: string) => void } = {}\n): AuthorizationRequirement {\n const { warn = true, logger = console.warn } = options;\n\n // Normalize 'oauth' to 'oauth2'\n if (auth.type === 'oauth') {\n if (warn) {\n logger(\n `DEPRECATION: Authorization type 'oauth' is deprecated and will be removed in v2.0.0. ` +\n `Please update to 'oauth2'. ` +\n `See https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/docs/migrations/oauth-to-oauth2.md`\n );\n }\n\n // Normalize to oauth2\n const normalized = {\n type: 'oauth2' as const,\n provider: auth.provider,\n ...(auth.requiredScopes !== undefined && { requiredScopes: auth.requiredScopes }),\n };\n\n return normalized;\n }\n\n // Normalize 'credential' to 'verifiable_credential'\n if (auth.type === 'credential') {\n if (warn) {\n logger(\n `DEPRECATION: Authorization type 'credential' is deprecated and will be removed in v2.0.0. ` +\n `Please update to 'verifiable_credential'. ` +\n `See https://github.com/modelcontextprotocol-identity/xmcp-i/blob/main/docs/migrations/credential-to-verifiable_credential.md`\n );\n }\n\n // Normalize to verifiable_credential\n const normalized = {\n type: 'verifiable_credential' as const,\n credentialType: auth.credentialType,\n ...(auth.issuer !== undefined && { issuer: auth.issuer }),\n };\n\n return normalized;\n }\n\n // No normalization needed\n return auth;\n}\n"],"mappings":";;;;AAyBA,MAAa,2BAA2B;AAExC,MAAM,iBAAiB;;AAGvB,MAAM,wBAAwB;AAE9B,SAAS,UAAU,OAAsC;CACvD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS,KAAK,MAAM,OAAO,SAAS,OAAO,SAAS,QAAQ,IAC7F,QACA;AACN;AAEA,SAAS,oBAAoB,SAA4B;CACvD,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;CACrC,MAAM,SAAS,QAAQ,SAAS,WAC9B,OAAO,WAAW,YAClB,WAAW,QACV,OAA8B,SAAS,YACxC,MAAM,QAAS,OAAgC,MAAM,IAC/C,OAAiC,OAAO,QACvC,UAAU,OAAO,UAAU,YAAY,MAAM,SAAS,CACzD,IACA,CAAC,CACP;CACA,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;;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AM;GACN,UAAU,KAAK;GACf,GAAI,KAAK,mBAAmB,UAAa,EAAE,gBAAgB,KAAK,eAAe;EAGjE;CAClB;CAGA,IAAI,KAAK,SAAS,cAAc;EAC9B,IAAI,MACF,OACE,kQAGF;EAUF,OAAO;GALL,MAAM;GACN,gBAAgB,KAAK;GACrB,GAAI,KAAK,WAAW,UAAa,EAAE,QAAQ,KAAK,OAAO;EAGzC;CAClB;CAGA,OAAO;AACT"}
@@ -0,0 +1,181 @@
1
+ //#region src/utils/verification.ts
2
+ /**
3
+ * KYA-OS verification-method vocabulary rename (`mcp-i` → `kya-os`), read side.
4
+ *
5
+ * Mirrors the Vocab-1 dual-accept shape in `policy/constants.ts`: a canonical
6
+ * value plus a deprecated legacy alias kept for a read-side cutover window.
7
+ * **This widens READERS only** — nothing emits the canonical value yet (the
8
+ * Rust engine still emits `mcp_i_handshake`; the gateway worker still emits the
9
+ * wire value `mcp-i`). The canonical spelling matches the `kyaos-jws` token
10
+ * chosen for the `verified_protocol` axis in #2937.
11
+ *
12
+ * Two distinct value spaces — do not conflate:
13
+ * - **ENGINE value** — emitted by the detection engine (`mcp_i_handshake`).
14
+ * - **WIRE value** — the normalized form stored/exposed downstream (`mcp-i`).
15
+ *
16
+ * This module is the SINGLE source of the legacy↔canonical alias map for both
17
+ * spaces. Every downstream "accept both" site routes through the predicates
18
+ * (`isKyaOs*Method`) or normalizers (`normalize*Method`) below, so the literal
19
+ * alias strings live in exactly one place; adding or retiring an alias is a
20
+ * one-file change, and no consumer can drift into a single-alias bypass.
21
+ */
22
+ const KYA_OS_HANDSHAKE_METHODS = {
23
+ /** New canonical engine value. Not emitted yet — accepted on read. */
24
+ CANONICAL: "kyaos_handshake",
25
+ /** @deprecated Legacy engine value. Still emitted by the Rust engine. */
26
+ LEGACY: "mcp_i_handshake"
27
+ };
28
+ const KYA_OS_WIRE_METHODS = {
29
+ /** New canonical wire value. Not emitted yet — accepted on read. */
30
+ CANONICAL: "kya-os",
31
+ /** @deprecated Legacy wire value. Still emitted by the gateway worker. */
32
+ LEGACY: "mcp-i"
33
+ };
34
+ /** True for either the legacy or canonical KYA-OS handshake ENGINE value. */
35
+ function isKyaOsHandshakeMethod(value) {
36
+ return value === KYA_OS_HANDSHAKE_METHODS.LEGACY || value === KYA_OS_HANDSHAKE_METHODS.CANONICAL;
37
+ }
38
+ /** True for either the legacy or canonical KYA-OS delegation WIRE value. */
39
+ function isKyaOsWireMethod(value) {
40
+ return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;
41
+ }
42
+ /**
43
+ * Collapse a KYA-OS handshake ENGINE value to its canonical form for INTERNAL
44
+ * comparison. Either alias (`mcp_i_handshake` | `kyaos_handshake`) maps to
45
+ * `KYA_OS_HANDSHAKE_METHODS.CANONICAL`; every other value (including
46
+ * null/undefined) passes through unchanged. The return type widens the caller's
47
+ * type by the canonical alias (`T | 'kyaos_handshake'`), which is honest (no
48
+ * `as` cast) and still drops cleanly into a typed `switch`.
49
+ *
50
+ * Use this to normalize ONCE at a boundary so downstream decisions compare a
51
+ * single value instead of re-listing both aliases. It does NOT touch the wire
52
+ * value space; a wire value like `mcp-i` passes straight through.
53
+ *
54
+ * SECURITY/DATA NOTE: this is for comparison/decisions only. Do NOT use it to
55
+ * rewrite a value that gets PERSISTED or EMITTED. Historical DB rows, the Rust
56
+ * engine, and the gateway worker all still use the legacy spelling, so changing
57
+ * a stored/emitted value would be a data-format change. Sites that map to a
58
+ * stored/wire value keep emitting the legacy value deliberately.
59
+ */
60
+ function normalizeHandshakeMethod(value) {
61
+ return isKyaOsHandshakeMethod(value) ? KYA_OS_HANDSHAKE_METHODS.CANONICAL : value;
62
+ }
63
+ /**
64
+ * Collapse a KYA-OS delegation WIRE value to its canonical form for INTERNAL
65
+ * comparison. Either alias (`mcp-i` | `kya-os`) maps to
66
+ * `KYA_OS_WIRE_METHODS.CANONICAL`; every other value (including null/undefined)
67
+ * passes through unchanged. Does NOT touch the engine value space.
68
+ *
69
+ * Same comparison-only contract and honest `T | 'kya-os'` return type as
70
+ * `normalizeHandshakeMethod`; never use it to change a persisted/emitted value.
71
+ */
72
+ function normalizeWireMethod(value) {
73
+ return isKyaOsWireMethod(value) ? KYA_OS_WIRE_METHODS.CANONICAL : value;
74
+ }
75
+ /**
76
+ * Gets a human-readable description for a verification method
77
+ */
78
+ function getVerificationMethodDescription(method) {
79
+ switch (normalizeHandshakeMethod(method)) {
80
+ case "signature": return "HTTP Signature Verification";
81
+ case "pattern": return "User-Agent Pattern Matching";
82
+ case "behavioral": return "Behavioral Analysis";
83
+ case "network": return "Network-based Detection";
84
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL: return "MCP Handshake Detection";
85
+ case "error": return "Detection Error";
86
+ default: return "No Verification";
87
+ }
88
+ }
89
+ /**
90
+ * Gets the reliability/confidence modifier for a verification method
91
+ * Higher values indicate more reliable verification methods
92
+ */
93
+ function getVerificationReliability(method) {
94
+ switch (normalizeHandshakeMethod(method)) {
95
+ case "signature": return 1;
96
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL: return .95;
97
+ case "behavioral": return .8;
98
+ case "network": return .6;
99
+ case "pattern": return .5;
100
+ case "none": return .3;
101
+ default: return .1;
102
+ }
103
+ }
104
+ /**
105
+ * Determines if a verification method indicates high confidence detection
106
+ */
107
+ function isHighConfidenceVerification(method) {
108
+ return method === "signature" || isKyaOsHandshakeMethod(method);
109
+ }
110
+ /**
111
+ * Maps verification method to appropriate risk level
112
+ */
113
+ function getVerificationRiskLevel(method, confidence) {
114
+ if (method === "signature") return "low";
115
+ if (isKyaOsHandshakeMethod(method)) return "low";
116
+ if (confidence >= .9) return method === "behavioral" ? "medium" : "high";
117
+ if (confidence >= .7) return "medium";
118
+ return "high";
119
+ }
120
+
121
+ //#endregion
122
+ Object.defineProperty(exports, 'KYA_OS_HANDSHAKE_METHODS', {
123
+ enumerable: true,
124
+ get: function () {
125
+ return KYA_OS_HANDSHAKE_METHODS;
126
+ }
127
+ });
128
+ Object.defineProperty(exports, 'KYA_OS_WIRE_METHODS', {
129
+ enumerable: true,
130
+ get: function () {
131
+ return KYA_OS_WIRE_METHODS;
132
+ }
133
+ });
134
+ Object.defineProperty(exports, 'getVerificationMethodDescription', {
135
+ enumerable: true,
136
+ get: function () {
137
+ return getVerificationMethodDescription;
138
+ }
139
+ });
140
+ Object.defineProperty(exports, 'getVerificationReliability', {
141
+ enumerable: true,
142
+ get: function () {
143
+ return getVerificationReliability;
144
+ }
145
+ });
146
+ Object.defineProperty(exports, 'getVerificationRiskLevel', {
147
+ enumerable: true,
148
+ get: function () {
149
+ return getVerificationRiskLevel;
150
+ }
151
+ });
152
+ Object.defineProperty(exports, 'isHighConfidenceVerification', {
153
+ enumerable: true,
154
+ get: function () {
155
+ return isHighConfidenceVerification;
156
+ }
157
+ });
158
+ Object.defineProperty(exports, 'isKyaOsHandshakeMethod', {
159
+ enumerable: true,
160
+ get: function () {
161
+ return isKyaOsHandshakeMethod;
162
+ }
163
+ });
164
+ Object.defineProperty(exports, 'isKyaOsWireMethod', {
165
+ enumerable: true,
166
+ get: function () {
167
+ return isKyaOsWireMethod;
168
+ }
169
+ });
170
+ Object.defineProperty(exports, 'normalizeHandshakeMethod', {
171
+ enumerable: true,
172
+ get: function () {
173
+ return normalizeHandshakeMethod;
174
+ }
175
+ });
176
+ Object.defineProperty(exports, 'normalizeWireMethod', {
177
+ enumerable: true,
178
+ get: function () {
179
+ return normalizeWireMethod;
180
+ }
181
+ });
@@ -0,0 +1,123 @@
1
+ //#region src/utils/verification.ts
2
+ /**
3
+ * KYA-OS verification-method vocabulary rename (`mcp-i` → `kya-os`), read side.
4
+ *
5
+ * Mirrors the Vocab-1 dual-accept shape in `policy/constants.ts`: a canonical
6
+ * value plus a deprecated legacy alias kept for a read-side cutover window.
7
+ * **This widens READERS only** — nothing emits the canonical value yet (the
8
+ * Rust engine still emits `mcp_i_handshake`; the gateway worker still emits the
9
+ * wire value `mcp-i`). The canonical spelling matches the `kyaos-jws` token
10
+ * chosen for the `verified_protocol` axis in #2937.
11
+ *
12
+ * Two distinct value spaces — do not conflate:
13
+ * - **ENGINE value** — emitted by the detection engine (`mcp_i_handshake`).
14
+ * - **WIRE value** — the normalized form stored/exposed downstream (`mcp-i`).
15
+ *
16
+ * This module is the SINGLE source of the legacy↔canonical alias map for both
17
+ * spaces. Every downstream "accept both" site routes through the predicates
18
+ * (`isKyaOs*Method`) or normalizers (`normalize*Method`) below, so the literal
19
+ * alias strings live in exactly one place; adding or retiring an alias is a
20
+ * one-file change, and no consumer can drift into a single-alias bypass.
21
+ */
22
+ const KYA_OS_HANDSHAKE_METHODS = {
23
+ /** New canonical engine value. Not emitted yet — accepted on read. */
24
+ CANONICAL: "kyaos_handshake",
25
+ /** @deprecated Legacy engine value. Still emitted by the Rust engine. */
26
+ LEGACY: "mcp_i_handshake"
27
+ };
28
+ const KYA_OS_WIRE_METHODS = {
29
+ /** New canonical wire value. Not emitted yet — accepted on read. */
30
+ CANONICAL: "kya-os",
31
+ /** @deprecated Legacy wire value. Still emitted by the gateway worker. */
32
+ LEGACY: "mcp-i"
33
+ };
34
+ /** True for either the legacy or canonical KYA-OS handshake ENGINE value. */
35
+ function isKyaOsHandshakeMethod(value) {
36
+ return value === KYA_OS_HANDSHAKE_METHODS.LEGACY || value === KYA_OS_HANDSHAKE_METHODS.CANONICAL;
37
+ }
38
+ /** True for either the legacy or canonical KYA-OS delegation WIRE value. */
39
+ function isKyaOsWireMethod(value) {
40
+ return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;
41
+ }
42
+ /**
43
+ * Collapse a KYA-OS handshake ENGINE value to its canonical form for INTERNAL
44
+ * comparison. Either alias (`mcp_i_handshake` | `kyaos_handshake`) maps to
45
+ * `KYA_OS_HANDSHAKE_METHODS.CANONICAL`; every other value (including
46
+ * null/undefined) passes through unchanged. The return type widens the caller's
47
+ * type by the canonical alias (`T | 'kyaos_handshake'`), which is honest (no
48
+ * `as` cast) and still drops cleanly into a typed `switch`.
49
+ *
50
+ * Use this to normalize ONCE at a boundary so downstream decisions compare a
51
+ * single value instead of re-listing both aliases. It does NOT touch the wire
52
+ * value space; a wire value like `mcp-i` passes straight through.
53
+ *
54
+ * SECURITY/DATA NOTE: this is for comparison/decisions only. Do NOT use it to
55
+ * rewrite a value that gets PERSISTED or EMITTED. Historical DB rows, the Rust
56
+ * engine, and the gateway worker all still use the legacy spelling, so changing
57
+ * a stored/emitted value would be a data-format change. Sites that map to a
58
+ * stored/wire value keep emitting the legacy value deliberately.
59
+ */
60
+ function normalizeHandshakeMethod(value) {
61
+ return isKyaOsHandshakeMethod(value) ? KYA_OS_HANDSHAKE_METHODS.CANONICAL : value;
62
+ }
63
+ /**
64
+ * Collapse a KYA-OS delegation WIRE value to its canonical form for INTERNAL
65
+ * comparison. Either alias (`mcp-i` | `kya-os`) maps to
66
+ * `KYA_OS_WIRE_METHODS.CANONICAL`; every other value (including null/undefined)
67
+ * passes through unchanged. Does NOT touch the engine value space.
68
+ *
69
+ * Same comparison-only contract and honest `T | 'kya-os'` return type as
70
+ * `normalizeHandshakeMethod`; never use it to change a persisted/emitted value.
71
+ */
72
+ function normalizeWireMethod(value) {
73
+ return isKyaOsWireMethod(value) ? KYA_OS_WIRE_METHODS.CANONICAL : value;
74
+ }
75
+ /**
76
+ * Gets a human-readable description for a verification method
77
+ */
78
+ function getVerificationMethodDescription(method) {
79
+ switch (normalizeHandshakeMethod(method)) {
80
+ case "signature": return "HTTP Signature Verification";
81
+ case "pattern": return "User-Agent Pattern Matching";
82
+ case "behavioral": return "Behavioral Analysis";
83
+ case "network": return "Network-based Detection";
84
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL: return "MCP Handshake Detection";
85
+ case "error": return "Detection Error";
86
+ default: return "No Verification";
87
+ }
88
+ }
89
+ /**
90
+ * Gets the reliability/confidence modifier for a verification method
91
+ * Higher values indicate more reliable verification methods
92
+ */
93
+ function getVerificationReliability(method) {
94
+ switch (normalizeHandshakeMethod(method)) {
95
+ case "signature": return 1;
96
+ case KYA_OS_HANDSHAKE_METHODS.CANONICAL: return .95;
97
+ case "behavioral": return .8;
98
+ case "network": return .6;
99
+ case "pattern": return .5;
100
+ case "none": return .3;
101
+ default: return .1;
102
+ }
103
+ }
104
+ /**
105
+ * Determines if a verification method indicates high confidence detection
106
+ */
107
+ function isHighConfidenceVerification(method) {
108
+ return method === "signature" || isKyaOsHandshakeMethod(method);
109
+ }
110
+ /**
111
+ * Maps verification method to appropriate risk level
112
+ */
113
+ function getVerificationRiskLevel(method, confidence) {
114
+ if (method === "signature") return "low";
115
+ if (isKyaOsHandshakeMethod(method)) return "low";
116
+ if (confidence >= .9) return method === "behavioral" ? "medium" : "high";
117
+ if (confidence >= .7) return "medium";
118
+ return "high";
119
+ }
120
+
121
+ //#endregion
122
+ export { getVerificationRiskLevel as a, isKyaOsWireMethod as c, getVerificationReliability as i, normalizeHandshakeMethod as l, KYA_OS_WIRE_METHODS as n, isHighConfidenceVerification as o, getVerificationMethodDescription as r, isKyaOsHandshakeMethod as s, KYA_OS_HANDSHAKE_METHODS as t, normalizeWireMethod as u };
123
+ //# sourceMappingURL=verification-Cvvv86TT.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verification-Cvvv86TT.mjs","names":[],"sources":["../src/utils/verification.ts"],"sourcesContent":["/**\n * Shared utilities for verification method mapping and handling\n */\n\nexport type VerificationMethod =\n | 'signature'\n | 'pattern'\n | 'behavioral'\n | 'network'\n | 'mcp_i_handshake'\n | 'kyaos_handshake'\n | 'none'\n | 'error';\n\n/**\n * KYA-OS verification-method vocabulary rename (`mcp-i` → `kya-os`), read side.\n *\n * Mirrors the Vocab-1 dual-accept shape in `policy/constants.ts`: a canonical\n * value plus a deprecated legacy alias kept for a read-side cutover window.\n * **This widens READERS only** — nothing emits the canonical value yet (the\n * Rust engine still emits `mcp_i_handshake`; the gateway worker still emits the\n * wire value `mcp-i`). The canonical spelling matches the `kyaos-jws` token\n * chosen for the `verified_protocol` axis in #2937.\n *\n * Two distinct value spaces — do not conflate:\n * - **ENGINE value** — emitted by the detection engine (`mcp_i_handshake`).\n * - **WIRE value** — the normalized form stored/exposed downstream (`mcp-i`).\n *\n * This module is the SINGLE source of the legacy↔canonical alias map for both\n * spaces. Every downstream \"accept both\" site routes through the predicates\n * (`isKyaOs*Method`) or normalizers (`normalize*Method`) below, so the literal\n * alias strings live in exactly one place; adding or retiring an alias is a\n * one-file change, and no consumer can drift into a single-alias bypass.\n */\nexport const KYA_OS_HANDSHAKE_METHODS = {\n /** New canonical engine value. Not emitted yet — accepted on read. */\n CANONICAL: 'kyaos_handshake',\n /** @deprecated Legacy engine value. Still emitted by the Rust engine. */\n LEGACY: 'mcp_i_handshake',\n} as const;\n\nexport const KYA_OS_WIRE_METHODS = {\n /** New canonical wire value. Not emitted yet — accepted on read. */\n CANONICAL: 'kya-os',\n /** @deprecated Legacy wire value. Still emitted by the gateway worker. */\n LEGACY: 'mcp-i',\n} as const;\n\n/** True for either the legacy or canonical KYA-OS handshake ENGINE value. */\nexport function isKyaOsHandshakeMethod(value: string | null | undefined): boolean {\n return value === KYA_OS_HANDSHAKE_METHODS.LEGACY || value === KYA_OS_HANDSHAKE_METHODS.CANONICAL;\n}\n\n/** True for either the legacy or canonical KYA-OS delegation WIRE value. */\nexport function isKyaOsWireMethod(value: string | null | undefined): boolean {\n return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;\n}\n\n/**\n * Collapse a KYA-OS handshake ENGINE value to its canonical form for INTERNAL\n * comparison. Either alias (`mcp_i_handshake` | `kyaos_handshake`) maps to\n * `KYA_OS_HANDSHAKE_METHODS.CANONICAL`; every other value (including\n * null/undefined) passes through unchanged. The return type widens the caller's\n * type by the canonical alias (`T | 'kyaos_handshake'`), which is honest (no\n * `as` cast) and still drops cleanly into a typed `switch`.\n *\n * Use this to normalize ONCE at a boundary so downstream decisions compare a\n * single value instead of re-listing both aliases. It does NOT touch the wire\n * value space; a wire value like `mcp-i` passes straight through.\n *\n * SECURITY/DATA NOTE: this is for comparison/decisions only. Do NOT use it to\n * rewrite a value that gets PERSISTED or EMITTED. Historical DB rows, the Rust\n * engine, and the gateway worker all still use the legacy spelling, so changing\n * a stored/emitted value would be a data-format change. Sites that map to a\n * stored/wire value keep emitting the legacy value deliberately.\n */\nexport function normalizeHandshakeMethod<T extends string | null | undefined>(\n value: T\n): T | typeof KYA_OS_HANDSHAKE_METHODS.CANONICAL {\n return isKyaOsHandshakeMethod(value) ? KYA_OS_HANDSHAKE_METHODS.CANONICAL : value;\n}\n\n/**\n * Collapse a KYA-OS delegation WIRE value to its canonical form for INTERNAL\n * comparison. Either alias (`mcp-i` | `kya-os`) maps to\n * `KYA_OS_WIRE_METHODS.CANONICAL`; every other value (including null/undefined)\n * passes through unchanged. Does NOT touch the engine value space.\n *\n * Same comparison-only contract and honest `T | 'kya-os'` return type as\n * `normalizeHandshakeMethod`; never use it to change a persisted/emitted value.\n */\nexport function normalizeWireMethod<T extends string | null | undefined>(\n value: T\n): T | typeof KYA_OS_WIRE_METHODS.CANONICAL {\n return isKyaOsWireMethod(value) ? KYA_OS_WIRE_METHODS.CANONICAL : value;\n}\n\n/**\n * Gets a human-readable description for a verification method\n */\nexport function getVerificationMethodDescription(method: VerificationMethod): string {\n // Normalize the handshake alias pair to canonical FIRST, so only the\n // canonical case is listed here; the legacy-to-canonical map lives solely in\n // `normalizeHandshakeMethod`.\n switch (normalizeHandshakeMethod(method)) {\n case 'signature':\n return 'HTTP Signature Verification';\n case 'pattern':\n return 'User-Agent Pattern Matching';\n case 'behavioral':\n return 'Behavioral Analysis';\n case 'network':\n return 'Network-based Detection';\n case KYA_OS_HANDSHAKE_METHODS.CANONICAL:\n return 'MCP Handshake Detection';\n case 'error':\n return 'Detection Error';\n case 'none':\n default:\n return 'No Verification';\n }\n}\n\n/**\n * Gets the reliability/confidence modifier for a verification method\n * Higher values indicate more reliable verification methods\n */\nexport function getVerificationReliability(method: VerificationMethod): number {\n // Normalize the handshake alias pair to canonical FIRST (see above).\n switch (normalizeHandshakeMethod(method)) {\n case 'signature':\n return 1.0; // Highest reliability\n case KYA_OS_HANDSHAKE_METHODS.CANONICAL:\n return 0.95;\n case 'behavioral':\n return 0.8;\n case 'network':\n return 0.6;\n case 'pattern':\n return 0.5;\n case 'none':\n return 0.3;\n case 'error':\n default:\n return 0.1; // Lowest reliability\n }\n}\n\n/**\n * Determines if a verification method indicates high confidence detection\n */\nexport function isHighConfidenceVerification(method: VerificationMethod): boolean {\n // Dual-accept via the shared predicate (legacy + canonical handshake).\n return method === 'signature' || isKyaOsHandshakeMethod(method);\n}\n\n/**\n * Maps verification method to appropriate risk level\n */\nexport function getVerificationRiskLevel(\n method: VerificationMethod,\n confidence: number\n): 'low' | 'medium' | 'high' {\n if (method === 'signature') {\n return 'low'; // Signatures are hard to forge\n }\n\n // Dual-accept via the shared predicate (legacy + canonical handshake).\n if (isKyaOsHandshakeMethod(method)) {\n return 'low'; // MCP handshakes are reliable\n }\n\n if (confidence >= 0.9) {\n return method === 'behavioral' ? 'medium' : 'high';\n }\n\n if (confidence >= 0.7) {\n return 'medium';\n }\n\n return 'high'; // Low confidence = high risk of false positive\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,2BAA2B;;CAEtC,WAAW;;CAEX,QAAQ;AACV;AAEA,MAAa,sBAAsB;;CAEjC,WAAW;;CAEX,QAAQ;AACV;;AAGA,SAAgB,uBAAuB,OAA2C;CAChF,OAAO,UAAU,yBAAyB,UAAU,UAAU,yBAAyB;AACzF;;AAGA,SAAgB,kBAAkB,OAA2C;CAC3E,OAAO,UAAU,oBAAoB,UAAU,UAAU,oBAAoB;AAC/E;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,yBACd,OAC+C;CAC/C,OAAO,uBAAuB,KAAK,IAAI,yBAAyB,YAAY;AAC9E;;;;;;;;;;AAWA,SAAgB,oBACd,OAC0C;CAC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