@fgv/ts-extras 5.1.0-2 → 5.1.0-20

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 (264) hide show
  1. package/dist/index.browser.js +2 -1
  2. package/dist/index.browser.js.map +1 -0
  3. package/dist/index.js.map +1 -0
  4. package/dist/packlets/ai-assist/apiClient.js +792 -57
  5. package/dist/packlets/ai-assist/apiClient.js.map +1 -0
  6. package/dist/packlets/ai-assist/chatRequestBuilders.js +180 -0
  7. package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
  8. package/dist/packlets/ai-assist/converters.js.map +1 -0
  9. package/dist/packlets/ai-assist/index.js +4 -3
  10. package/dist/packlets/ai-assist/index.js.map +1 -0
  11. package/dist/packlets/ai-assist/model.js +20 -3
  12. package/dist/packlets/ai-assist/model.js.map +1 -0
  13. package/dist/packlets/ai-assist/registry.js +111 -10
  14. package/dist/packlets/ai-assist/registry.js.map +1 -0
  15. package/dist/packlets/ai-assist/sseParser.js +122 -0
  16. package/dist/packlets/ai-assist/sseParser.js.map +1 -0
  17. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js +192 -0
  18. package/dist/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
  19. package/dist/packlets/ai-assist/streamingAdapters/common.js +77 -0
  20. package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
  21. package/dist/packlets/ai-assist/streamingAdapters/gemini.js +160 -0
  22. package/dist/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
  23. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js +149 -0
  24. package/dist/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
  25. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js +163 -0
  26. package/dist/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
  27. package/dist/packlets/ai-assist/streamingAdapters/proxy.js +157 -0
  28. package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
  29. package/dist/packlets/ai-assist/streamingClient.js +88 -0
  30. package/dist/packlets/ai-assist/streamingClient.js.map +1 -0
  31. package/dist/packlets/ai-assist/toolFormats.js.map +1 -0
  32. package/dist/packlets/conversion/converters.js +34 -1
  33. package/dist/packlets/conversion/converters.js.map +1 -0
  34. package/dist/packlets/conversion/index.js.map +1 -0
  35. package/dist/packlets/crypto-utils/constants.js.map +1 -0
  36. package/dist/packlets/crypto-utils/converters.js.map +1 -0
  37. package/dist/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
  38. package/dist/packlets/crypto-utils/encryptedFile.js.map +1 -0
  39. package/dist/packlets/crypto-utils/index.browser.js +2 -0
  40. package/dist/packlets/crypto-utils/index.browser.js.map +1 -0
  41. package/dist/packlets/crypto-utils/index.js +2 -0
  42. package/dist/packlets/crypto-utils/index.js.map +1 -0
  43. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js +57 -0
  44. package/dist/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
  45. package/dist/packlets/crypto-utils/keystore/converters.js +101 -9
  46. package/dist/packlets/crypto-utils/keystore/converters.js.map +1 -0
  47. package/dist/packlets/crypto-utils/keystore/index.js +1 -0
  48. package/dist/packlets/crypto-utils/keystore/index.js.map +1 -0
  49. package/dist/packlets/crypto-utils/keystore/keyStore.js +431 -118
  50. package/dist/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
  51. package/dist/packlets/crypto-utils/keystore/model.js +22 -1
  52. package/dist/packlets/crypto-utils/keystore/model.js.map +1 -0
  53. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js +21 -0
  54. package/dist/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
  55. package/dist/packlets/crypto-utils/model.js +9 -0
  56. package/dist/packlets/crypto-utils/model.js.map +1 -0
  57. package/dist/packlets/crypto-utils/nodeCryptoProvider.js +152 -1
  58. package/dist/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
  59. package/dist/packlets/csv/csvFileHelpers.js.map +1 -0
  60. package/dist/packlets/csv/csvHelpers.js.map +1 -0
  61. package/dist/packlets/csv/index.browser.js.map +1 -0
  62. package/dist/packlets/csv/index.js.map +1 -0
  63. package/dist/packlets/experimental/extendedArray.js.map +1 -0
  64. package/dist/packlets/experimental/formatter.js.map +1 -0
  65. package/dist/packlets/experimental/index.js.map +1 -0
  66. package/dist/packlets/experimental/rangeOf.js.map +1 -0
  67. package/dist/packlets/hash/index.browser.js.map +1 -0
  68. package/dist/packlets/hash/index.js.map +1 -0
  69. package/dist/packlets/hash/index.node.js.map +1 -0
  70. package/dist/packlets/hash/md5Normalizer.browser.js.map +1 -0
  71. package/dist/packlets/hash/md5Normalizer.js.map +1 -0
  72. package/dist/packlets/mustache/index.js.map +1 -0
  73. package/dist/packlets/mustache/interfaces.js.map +1 -0
  74. package/dist/packlets/mustache/mustacheTemplate.js.map +1 -0
  75. package/dist/packlets/record-jar/index.browser.js.map +1 -0
  76. package/dist/packlets/record-jar/index.js.map +1 -0
  77. package/dist/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
  78. package/dist/packlets/record-jar/recordJarHelpers.js.map +1 -0
  79. package/dist/packlets/yaml/converters.js.map +1 -0
  80. package/dist/packlets/yaml/index.js +1 -0
  81. package/dist/packlets/yaml/index.js.map +1 -0
  82. package/dist/packlets/yaml/serializers.js +48 -0
  83. package/dist/packlets/yaml/serializers.js.map +1 -0
  84. package/dist/packlets/zip-file-tree/index.js.map +1 -0
  85. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  86. package/dist/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
  87. package/dist/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
  88. package/dist/ts-extras.d.ts +1442 -45
  89. package/dist/tsdoc-metadata.json +1 -1
  90. package/lib/index.browser.d.ts +2 -1
  91. package/lib/index.browser.d.ts.map +1 -0
  92. package/lib/index.browser.js +3 -1
  93. package/lib/index.browser.js.map +1 -0
  94. package/lib/index.d.ts.map +1 -0
  95. package/lib/index.js.map +1 -0
  96. package/lib/packlets/ai-assist/apiClient.d.ts +111 -1
  97. package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -0
  98. package/lib/packlets/ai-assist/apiClient.js +795 -56
  99. package/lib/packlets/ai-assist/apiClient.js.map +1 -0
  100. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +89 -0
  101. package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -0
  102. package/lib/packlets/ai-assist/chatRequestBuilders.js +189 -0
  103. package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -0
  104. package/lib/packlets/ai-assist/converters.d.ts.map +1 -0
  105. package/lib/packlets/ai-assist/converters.js.map +1 -0
  106. package/lib/packlets/ai-assist/index.d.ts +4 -3
  107. package/lib/packlets/ai-assist/index.d.ts.map +1 -0
  108. package/lib/packlets/ai-assist/index.js +12 -1
  109. package/lib/packlets/ai-assist/index.js.map +1 -0
  110. package/lib/packlets/ai-assist/model.d.ts +332 -2
  111. package/lib/packlets/ai-assist/model.d.ts.map +1 -0
  112. package/lib/packlets/ai-assist/model.js +21 -3
  113. package/lib/packlets/ai-assist/model.js.map +1 -0
  114. package/lib/packlets/ai-assist/registry.d.ts +34 -1
  115. package/lib/packlets/ai-assist/registry.d.ts.map +1 -0
  116. package/lib/packlets/ai-assist/registry.js +114 -11
  117. package/lib/packlets/ai-assist/registry.js.map +1 -0
  118. package/lib/packlets/ai-assist/sseParser.d.ts +45 -0
  119. package/lib/packlets/ai-assist/sseParser.d.ts.map +1 -0
  120. package/lib/packlets/ai-assist/sseParser.js +127 -0
  121. package/lib/packlets/ai-assist/sseParser.js.map +1 -0
  122. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts +18 -0
  123. package/lib/packlets/ai-assist/streamingAdapters/anthropic.d.ts.map +1 -0
  124. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js +195 -0
  125. package/lib/packlets/ai-assist/streamingAdapters/anthropic.js.map +1 -0
  126. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +71 -0
  127. package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -0
  128. package/lib/packlets/ai-assist/streamingAdapters/common.js +81 -0
  129. package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -0
  130. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts +19 -0
  131. package/lib/packlets/ai-assist/streamingAdapters/gemini.d.ts.map +1 -0
  132. package/lib/packlets/ai-assist/streamingAdapters/gemini.js +163 -0
  133. package/lib/packlets/ai-assist/streamingAdapters/gemini.js.map +1 -0
  134. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts +18 -0
  135. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.d.ts.map +1 -0
  136. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js +152 -0
  137. package/lib/packlets/ai-assist/streamingAdapters/openaiChat.js.map +1 -0
  138. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts +19 -0
  139. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.d.ts.map +1 -0
  140. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js +166 -0
  141. package/lib/packlets/ai-assist/streamingAdapters/openaiResponses.js.map +1 -0
  142. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts +34 -0
  143. package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -0
  144. package/lib/packlets/ai-assist/streamingAdapters/proxy.js +160 -0
  145. package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -0
  146. package/lib/packlets/ai-assist/streamingClient.d.ts +33 -0
  147. package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -0
  148. package/lib/packlets/ai-assist/streamingClient.js +93 -0
  149. package/lib/packlets/ai-assist/streamingClient.js.map +1 -0
  150. package/lib/packlets/ai-assist/toolFormats.d.ts.map +1 -0
  151. package/lib/packlets/ai-assist/toolFormats.js.map +1 -0
  152. package/lib/packlets/conversion/converters.d.ts +8 -1
  153. package/lib/packlets/conversion/converters.d.ts.map +1 -0
  154. package/lib/packlets/conversion/converters.js +35 -2
  155. package/lib/packlets/conversion/converters.js.map +1 -0
  156. package/lib/packlets/conversion/index.d.ts.map +1 -0
  157. package/lib/packlets/conversion/index.js.map +1 -0
  158. package/lib/packlets/crypto-utils/constants.d.ts.map +1 -0
  159. package/lib/packlets/crypto-utils/constants.js.map +1 -0
  160. package/lib/packlets/crypto-utils/converters.d.ts.map +1 -0
  161. package/lib/packlets/crypto-utils/converters.js.map +1 -0
  162. package/lib/packlets/crypto-utils/directEncryptionProvider.d.ts.map +1 -0
  163. package/lib/packlets/crypto-utils/directEncryptionProvider.js.map +1 -0
  164. package/lib/packlets/crypto-utils/encryptedFile.d.ts.map +1 -0
  165. package/lib/packlets/crypto-utils/encryptedFile.js.map +1 -0
  166. package/lib/packlets/crypto-utils/index.browser.d.ts +1 -0
  167. package/lib/packlets/crypto-utils/index.browser.d.ts.map +1 -0
  168. package/lib/packlets/crypto-utils/index.browser.js +4 -1
  169. package/lib/packlets/crypto-utils/index.browser.js.map +1 -0
  170. package/lib/packlets/crypto-utils/index.d.ts +1 -0
  171. package/lib/packlets/crypto-utils/index.d.ts.map +1 -0
  172. package/lib/packlets/crypto-utils/index.js +4 -1
  173. package/lib/packlets/crypto-utils/index.js.map +1 -0
  174. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts +39 -0
  175. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.d.ts.map +1 -0
  176. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js +60 -0
  177. package/lib/packlets/crypto-utils/keyPairAlgorithmParams.js.map +1 -0
  178. package/lib/packlets/crypto-utils/keystore/converters.d.ts +68 -6
  179. package/lib/packlets/crypto-utils/keystore/converters.d.ts.map +1 -0
  180. package/lib/packlets/crypto-utils/keystore/converters.js +100 -8
  181. package/lib/packlets/crypto-utils/keystore/converters.js.map +1 -0
  182. package/lib/packlets/crypto-utils/keystore/index.d.ts +1 -0
  183. package/lib/packlets/crypto-utils/keystore/index.d.ts.map +1 -0
  184. package/lib/packlets/crypto-utils/keystore/index.js +1 -0
  185. package/lib/packlets/crypto-utils/keystore/index.js.map +1 -0
  186. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts +125 -12
  187. package/lib/packlets/crypto-utils/keystore/keyStore.d.ts.map +1 -0
  188. package/lib/packlets/crypto-utils/keystore/keyStore.js +431 -118
  189. package/lib/packlets/crypto-utils/keystore/keyStore.js.map +1 -0
  190. package/lib/packlets/crypto-utils/keystore/model.d.ts +248 -17
  191. package/lib/packlets/crypto-utils/keystore/model.d.ts.map +1 -0
  192. package/lib/packlets/crypto-utils/keystore/model.js +24 -2
  193. package/lib/packlets/crypto-utils/keystore/model.js.map +1 -0
  194. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts +50 -0
  195. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.d.ts.map +1 -0
  196. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js +22 -0
  197. package/lib/packlets/crypto-utils/keystore/privateKeyStorage.js.map +1 -0
  198. package/lib/packlets/crypto-utils/model.d.ts +140 -0
  199. package/lib/packlets/crypto-utils/model.d.ts.map +1 -0
  200. package/lib/packlets/crypto-utils/model.js +10 -1
  201. package/lib/packlets/crypto-utils/model.js.map +1 -0
  202. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts +51 -1
  203. package/lib/packlets/crypto-utils/nodeCryptoProvider.d.ts.map +1 -0
  204. package/lib/packlets/crypto-utils/nodeCryptoProvider.js +151 -0
  205. package/lib/packlets/crypto-utils/nodeCryptoProvider.js.map +1 -0
  206. package/lib/packlets/csv/csvFileHelpers.d.ts.map +1 -0
  207. package/lib/packlets/csv/csvFileHelpers.js.map +1 -0
  208. package/lib/packlets/csv/csvHelpers.d.ts.map +1 -0
  209. package/lib/packlets/csv/csvHelpers.js.map +1 -0
  210. package/lib/packlets/csv/index.browser.d.ts.map +1 -0
  211. package/lib/packlets/csv/index.browser.js.map +1 -0
  212. package/lib/packlets/csv/index.d.ts.map +1 -0
  213. package/lib/packlets/csv/index.js.map +1 -0
  214. package/lib/packlets/experimental/extendedArray.d.ts.map +1 -0
  215. package/lib/packlets/experimental/extendedArray.js.map +1 -0
  216. package/lib/packlets/experimental/formatter.d.ts.map +1 -0
  217. package/lib/packlets/experimental/formatter.js.map +1 -0
  218. package/lib/packlets/experimental/index.d.ts.map +1 -0
  219. package/lib/packlets/experimental/index.js.map +1 -0
  220. package/lib/packlets/experimental/rangeOf.d.ts.map +1 -0
  221. package/lib/packlets/experimental/rangeOf.js.map +1 -0
  222. package/lib/packlets/hash/index.browser.d.ts.map +1 -0
  223. package/lib/packlets/hash/index.browser.js.map +1 -0
  224. package/lib/packlets/hash/index.d.ts.map +1 -0
  225. package/lib/packlets/hash/index.js.map +1 -0
  226. package/lib/packlets/hash/index.node.d.ts.map +1 -0
  227. package/lib/packlets/hash/index.node.js.map +1 -0
  228. package/lib/packlets/hash/md5Normalizer.browser.d.ts.map +1 -0
  229. package/lib/packlets/hash/md5Normalizer.browser.js.map +1 -0
  230. package/lib/packlets/hash/md5Normalizer.d.ts.map +1 -0
  231. package/lib/packlets/hash/md5Normalizer.js.map +1 -0
  232. package/lib/packlets/mustache/index.d.ts.map +1 -0
  233. package/lib/packlets/mustache/index.js.map +1 -0
  234. package/lib/packlets/mustache/interfaces.d.ts.map +1 -0
  235. package/lib/packlets/mustache/interfaces.js.map +1 -0
  236. package/lib/packlets/mustache/mustacheTemplate.d.ts.map +1 -0
  237. package/lib/packlets/mustache/mustacheTemplate.js.map +1 -0
  238. package/lib/packlets/record-jar/index.browser.d.ts.map +1 -0
  239. package/lib/packlets/record-jar/index.browser.js.map +1 -0
  240. package/lib/packlets/record-jar/index.d.ts.map +1 -0
  241. package/lib/packlets/record-jar/index.js.map +1 -0
  242. package/lib/packlets/record-jar/recordJarFileHelpers.d.ts.map +1 -0
  243. package/lib/packlets/record-jar/recordJarFileHelpers.js.map +1 -0
  244. package/lib/packlets/record-jar/recordJarHelpers.d.ts.map +1 -0
  245. package/lib/packlets/record-jar/recordJarHelpers.js.map +1 -0
  246. package/lib/packlets/yaml/converters.d.ts.map +1 -0
  247. package/lib/packlets/yaml/converters.js.map +1 -0
  248. package/lib/packlets/yaml/index.d.ts +1 -0
  249. package/lib/packlets/yaml/index.d.ts.map +1 -0
  250. package/lib/packlets/yaml/index.js +1 -0
  251. package/lib/packlets/yaml/index.js.map +1 -0
  252. package/lib/packlets/yaml/serializers.d.ts +45 -0
  253. package/lib/packlets/yaml/serializers.d.ts.map +1 -0
  254. package/lib/packlets/yaml/serializers.js +84 -0
  255. package/lib/packlets/yaml/serializers.js.map +1 -0
  256. package/lib/packlets/zip-file-tree/index.d.ts.map +1 -0
  257. package/lib/packlets/zip-file-tree/index.js.map +1 -0
  258. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts +2 -2
  259. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.d.ts.map +1 -0
  260. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js +2 -2
  261. package/lib/packlets/zip-file-tree/zipFileTreeAccessors.js.map +1 -0
  262. package/lib/packlets/zip-file-tree/zipFileTreeWriter.d.ts.map +1 -0
  263. package/lib/packlets/zip-file-tree/zipFileTreeWriter.js.map +1 -0
  264. package/package.json +24 -23
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keyStore.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/keyStore.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAGZ,OAAO,EAAE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C,EAAE,MAAM,YAAY,CAAC,OAAO,EAAE,CAAC;YAC7G,CAAC;YACD,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;;;OAIG;IACK,WAAW;QACjB,OAAO,IAAI,CAAC,eAAe,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,EAAE;YACtE,8DAA8D;YAC9D,sCAAsC;YACtC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;YACpC,sCAAsC;YACtC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;YACpC,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;iBAC1B,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;iBAC3C,IAAI,CAAC,EAAE,CAAC,CAAC;YACZ,OAAO,OAAO,CACZ,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,EAAE,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAC3F,EAAE,EACF,EAAE,CACH,EAAE,CACJ,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { captureResult, fail, Result, succeed } from '@fgv/ts-utils';\nimport * as Constants from '../constants';\nimport { createEncryptedFile } from '../encryptedFile';\nimport {\n ICryptoProvider,\n IEncryptedFile,\n IEncryptionConfig,\n IEncryptionProvider,\n SecretProvider\n} from '../model';\nimport {\n DEFAULT_KEYSTORE_ITERATIONS,\n DEFAULT_SECRET_ITERATIONS,\n IAddKeyPairOptions,\n IAddKeyPairResult,\n IAddSecretFromPasswordOptions,\n IAddSecretFromPasswordResult,\n IAddSecretOptions,\n IAddSecretResult,\n IImportKeyOptions,\n IImportSecretOptions,\n IKeyStoreAsymmetricEntry,\n IKeyStoreCreateParams,\n IKeyStoreEntry,\n IKeyStoreEntryJson,\n IKeyStoreFile,\n IKeyStoreOpenParams,\n IKeyStoreSymmetricEntry,\n IKeyStoreVaultContents,\n IRemoveSecretResult,\n KEYSTORE_FORMAT,\n KeyStoreLockState,\n KeyStoreSecretType,\n MIN_SALT_LENGTH\n} from './model';\nimport { IPrivateKeyStorage } from './privateKeyStorage';\nimport { keystoreFile, keystoreVaultContents } from './converters';\n\n/**\n * Gets the current ISO timestamp.\n */\nfunction getCurrentTimestamp(): string {\n return new Date().toISOString();\n}\n\n// ============================================================================\n// KeyStore Class\n// ============================================================================\n\n/**\n * Password-protected key store for managing encryption secrets.\n *\n * The KeyStore provides a secure vault for storing named encryption keys.\n * The vault is encrypted at rest using a master password via PBKDF2 key derivation.\n *\n * @example\n * ```typescript\n * // Create new key store\n * const keystore = KeyStore.create({ cryptoProvider: nodeCryptoProvider }).orThrow();\n * await keystore.initialize('master-password');\n *\n * // Add secrets\n * await keystore.addSecret('my-key', { description: 'Production key' });\n *\n * // Save to file\n * const fileContent = await keystore.save();\n *\n * // Later: Open existing key store\n * const keystore2 = KeyStore.open({\n * cryptoProvider: nodeCryptoProvider,\n * keystoreFile: fileContent.value\n * }).orThrow();\n * await keystore2.unlock('master-password');\n *\n * // Use as secret provider for encrypted file loading\n * const encryptionConfig = keystore2.getEncryptionConfig().orThrow();\n * ```\n *\n * @public\n */\nexport class KeyStore implements IEncryptionProvider {\n private readonly _cryptoProvider: ICryptoProvider;\n private readonly _privateKeyStorage: IPrivateKeyStorage | undefined;\n private readonly _iterations: number;\n private _keystoreFile: IKeyStoreFile | undefined;\n private _salt: Uint8Array | undefined;\n private _secrets: Map<string, IKeyStoreEntry> | undefined;\n private _state: KeyStoreLockState;\n private _dirty: boolean;\n private _isNew: boolean;\n\n private constructor(\n cryptoProvider: ICryptoProvider,\n iterations: number,\n keystoreFile: IKeyStoreFile | undefined,\n isNew: boolean,\n privateKeyStorage: IPrivateKeyStorage | undefined\n ) {\n this._cryptoProvider = cryptoProvider;\n this._privateKeyStorage = privateKeyStorage;\n this._iterations = iterations;\n this._keystoreFile = keystoreFile;\n this._state = 'locked';\n this._dirty = false;\n this._isNew = isNew;\n }\n\n // ============================================================================\n // Factory Methods\n // ============================================================================\n\n /**\n * Creates a new, empty key store.\n * Call `initialize(password)` to set the master password.\n * @param params - Creation parameters\n * @returns Success with new KeyStore instance, or Failure if parameters invalid\n * @public\n */\n public static create(params: IKeyStoreCreateParams): Result<KeyStore> {\n const iterations = params.iterations ?? DEFAULT_KEYSTORE_ITERATIONS;\n if (iterations < 1) {\n return fail('Iterations must be at least 1');\n }\n return succeed(\n new KeyStore(params.cryptoProvider, iterations, undefined, true, params.privateKeyStorage)\n );\n }\n\n /**\n * Opens an existing encrypted key store.\n * Call `unlock(password)` to decrypt and access secrets.\n * @param params - Open parameters including the encrypted file\n * @returns Success with KeyStore instance, or Failure if file format invalid\n * @public\n */\n public static open(params: IKeyStoreOpenParams): Result<KeyStore> {\n // Validate the file format\n const fileResult = keystoreFile.convert(params.keystoreFile);\n if (fileResult.isFailure()) {\n return fail(`Invalid key store file: ${fileResult.message}`);\n }\n\n const iterations = fileResult.value.keyDerivation.iterations;\n return succeed(\n new KeyStore(params.cryptoProvider, iterations, fileResult.value, false, params.privateKeyStorage)\n );\n }\n\n // ============================================================================\n // Lifecycle Methods\n // ============================================================================\n\n /**\n * Initializes a new key store with the master password.\n * Generates a random salt for key derivation.\n * Only valid for newly created (not opened) key stores.\n * @param password - The master password\n * @returns Success with this instance when initialized, Failure if already initialized or opened\n * @public\n */\n public async initialize(password: string): Promise<Result<KeyStore>> {\n if (!this._isNew) {\n return fail('Cannot initialize an opened key store - use unlock() instead');\n }\n if (this._state === 'unlocked') {\n return fail('Key store is already initialized');\n }\n if (!password || password.length === 0) {\n return fail('Password cannot be empty');\n }\n\n // Generate salt for this key store using crypto provider\n const saltResult = this._cryptoProvider.generateRandomBytes(MIN_SALT_LENGTH);\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (saltResult.isFailure()) {\n return fail(`Failed to generate salt: ${saltResult.message}`);\n }\n\n this._salt = saltResult.value;\n this._secrets = new Map();\n this._state = 'unlocked';\n this._dirty = true; // New store needs to be saved\n\n return succeed(this);\n }\n\n /**\n * Unlocks an existing key store with the master password.\n * Decrypts the vault and loads secrets into memory.\n * @param password - The master password\n * @returns Success with this instance when unlocked, Failure if password incorrect\n * @public\n */\n public async unlock(password: string): Promise<Result<KeyStore>> {\n if (this._isNew) {\n return fail('Cannot unlock a new key store - use initialize() instead');\n }\n /* c8 ignore next 6 - error paths tested but coverage intermittently missed */\n if (this._state === 'unlocked') {\n return fail('Key store is already unlocked');\n }\n if (!this._keystoreFile) {\n return fail('No key store file to unlock');\n }\n\n const keyDerivation = this._keystoreFile.keyDerivation;\n const saltResult = this._cryptoProvider.fromBase64(keyDerivation.salt);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (saltResult.isFailure()) {\n return fail(`Invalid salt in key store file: ${saltResult.message}`);\n }\n const salt = saltResult.value;\n\n // Derive the key from password\n const keyResult = await this._cryptoProvider.deriveKey(password, salt, keyDerivation.iterations);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (keyResult.isFailure()) {\n return fail(`Key derivation failed: ${keyResult.message}`);\n }\n\n return this._decryptVault(keyResult.value);\n }\n\n /**\n * Unlocks an existing key store with a pre-derived key, bypassing\n * PBKDF2 key derivation. Use this when the derived key has been\n * stored externally (e.g., in another key store) and the original\n * password is no longer available.\n *\n * The supplied key must have been derived from the correct password\n * using the key store file's own PBKDF2 parameters (salt and\n * iteration count).\n *\n * @param derivedKey - The pre-derived master key (32 bytes for AES-256)\n * @returns Success with this instance when unlocked, Failure if key is incorrect\n * @public\n */\n public async unlockWithKey(derivedKey: Uint8Array): Promise<Result<KeyStore>> {\n if (this._isNew) {\n return fail('Cannot unlock a new key store - use initialize() instead');\n }\n if (this._state === 'unlocked') {\n return fail('Key store is already unlocked');\n }\n if (derivedKey.length !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${derivedKey.length}`);\n }\n /* c8 ignore next 3 - defensive coding: unreachable via public API (open sets file, create sets isNew) */\n if (!this._keystoreFile) {\n return fail('No key store file to unlock');\n }\n\n return this._decryptVault(derivedKey);\n }\n\n /**\n * Locks the key store, clearing all secrets from memory.\n * @param force - If true, discards unsaved changes\n * @returns Success when locked, Failure if unsaved changes and !force\n * @public\n */\n public lock(force?: boolean): Result<KeyStore> {\n if (this._state === 'locked') {\n return succeed(this);\n }\n\n if (this._dirty && !force) {\n return fail('Unsaved changes - use force=true to discard or save() first');\n }\n\n // Clear secrets from memory (overwrite for security)\n if (this._secrets) {\n for (const entry of this._secrets.values()) {\n if (entry.type !== 'asymmetric-keypair') {\n entry.key.fill(0);\n }\n }\n this._secrets.clear();\n this._secrets = undefined;\n }\n\n this._state = 'locked';\n this._dirty = false;\n\n return succeed(this);\n }\n\n /**\n * Checks if the key store is unlocked.\n * @public\n */\n public get isUnlocked(): boolean {\n return this._state === 'unlocked';\n }\n\n /**\n * Checks if there are unsaved changes.\n * @public\n */\n public get isDirty(): boolean {\n return this._dirty;\n }\n\n /**\n * Whether this is a newly created key store (not opened from a file).\n * A new key store must be initialized with a password before use.\n * An opened key store must be unlocked with the existing password.\n * @public\n */\n public get isNew(): boolean {\n return this._isNew;\n }\n\n /**\n * Gets the current lock state.\n * @public\n */\n public get state(): KeyStoreLockState {\n return this._state;\n }\n\n /**\n * Gets the crypto provider used by this key store.\n * Available regardless of lock state.\n * @public\n */\n public get cryptoProvider(): ICryptoProvider {\n return this._cryptoProvider;\n }\n\n // ============================================================================\n // Secret Management\n // ============================================================================\n\n /**\n * Lists all secret names in the key store.\n * @returns Success with array of secret names, Failure if locked\n * @public\n */\n public listSecrets(): Result<readonly string[]> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n return succeed(Array.from(this._secrets.keys()));\n }\n\n /**\n * Gets a secret by name. Returns the {@link CryptoUtils.KeyStore.IKeyStoreEntry | discriminated union}\n * — callers must check `entry.type` before accessing `key`/`id` since asymmetric\n * entries carry no raw key material.\n * @param name - Name of the secret\n * @returns Success with secret entry, Failure if not found or locked\n * @public\n */\n public getSecret(name: string): Result<IKeyStoreEntry> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n const entry = this._secrets.get(name);\n if (!entry) {\n return fail(`Secret '${name}' not found`);\n }\n return succeed(entry);\n }\n\n /**\n * Returns the public-key JWK for an asymmetric-keypair entry.\n * Available without {@link CryptoUtils.KeyStore.IPrivateKeyStorage} since the\n * public key lives in the vault metadata directly.\n * @param name - Name of the entry\n * @returns Success with the JWK, Failure if not found, locked, or wrong type\n * @public\n */\n public getPublicKeyJwk(name: string): Result<JsonWebKey> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n const entry = this._secrets.get(name);\n if (!entry) {\n return fail(`Secret '${name}' not found`);\n }\n if (entry.type !== 'asymmetric-keypair') {\n return fail(`Secret '${name}' is not an asymmetric keypair (type: ${entry.type})`);\n }\n return succeed(entry.publicKeyJwk);\n }\n\n /**\n * Checks if a secret exists.\n * @param name - Name of the secret\n * @returns Success with boolean, Failure if locked\n * @public\n */\n public hasSecret(name: string): Result<boolean> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n return succeed(this._secrets.has(name));\n }\n\n /**\n * Adds a new secret with a randomly generated key.\n * @param name - Unique name for the secret\n * @param options - Optional description\n * @returns Success with the generated entry, Failure if locked or name invalid\n * @public\n */\n public async addSecret(name: string, options?: IAddSecretOptions): Promise<Result<IAddSecretResult>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n if (!name || name.length === 0) {\n return fail('Secret name cannot be empty');\n }\n\n // Generate a new random key\n const keyResult = await this._cryptoProvider.generateKey();\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (keyResult.isFailure()) {\n return fail(`Failed to generate key: ${keyResult.message}`);\n }\n\n const entry: IKeyStoreSymmetricEntry = {\n name,\n type: 'encryption-key',\n key: keyResult.value,\n description: options?.description,\n createdAt: getCurrentTimestamp()\n };\n\n const existing = this._secrets.get(name);\n const warning = existing ? await this._releaseEntryResources(existing) : undefined;\n\n this._secrets.set(name, entry);\n this._dirty = true;\n\n return succeed({ entry, replaced: existing !== undefined, warning });\n }\n\n /**\n * Imports raw 32-byte key material into the vault.\n *\n * Always validates that the key is exactly 32 bytes (AES-256). The optional\n * `type` field is a classification label stored with the entry; it does not\n * change the validation rules. For importing UTF-8 API key strings (variable\n * length), use {@link KeyStore.importApiKey} instead.\n *\n * @param name - Unique name for the secret\n * @param key - The 32-byte AES-256 key material\n * @param options - Optional type classification, description, whether to replace existing\n * @returns Success with entry, Failure if locked, key invalid, or exists and !replace\n * @public\n */\n public async importSecret(\n name: string,\n key: Uint8Array,\n options?: IImportKeyOptions\n ): Promise<Result<IAddSecretResult>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n if (!name || name.length === 0) {\n return fail('Secret name cannot be empty');\n }\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n const existing = this._secrets.get(name);\n if (existing && !options?.replace) {\n return fail(`Secret '${name}' already exists - use replace=true to overwrite`);\n }\n\n const entry: IKeyStoreSymmetricEntry = {\n name,\n type: options?.type ?? 'encryption-key',\n key: new Uint8Array(key), // Copy to prevent external modification\n description: options?.description,\n createdAt: getCurrentTimestamp()\n };\n\n const warning = existing ? await this._releaseEntryResources(existing) : undefined;\n this._secrets.set(name, entry);\n this._dirty = true;\n\n return succeed({ entry, replaced: existing !== undefined, warning });\n }\n\n /**\n * Adds a secret derived from a password using PBKDF2.\n *\n * Generates a random salt, derives a 32-byte AES-256 key from the password,\n * and stores it in the vault. Returns the key derivation parameters so they\n * can be stored alongside encrypted files, enabling decryption with just the\n * password (without unlocking the keystore).\n *\n * @param name - Unique name for the secret\n * @param password - Password to derive the key from\n * @param options - Optional description, iterations, replace flag\n * @returns Success with entry and keyDerivation params, Failure if locked or invalid\n * @public\n */\n public async addSecretFromPassword(\n name: string,\n password: string,\n options?: IAddSecretFromPasswordOptions\n ): Promise<Result<IAddSecretFromPasswordResult>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n if (!name || name.length === 0) {\n return fail('Secret name cannot be empty');\n }\n if (!password || password.length === 0) {\n return fail('Password cannot be empty');\n }\n\n const existing = this._secrets.get(name);\n if (existing && !options?.replace) {\n return fail(`Secret '${name}' already exists - use replace=true to overwrite`);\n }\n\n const iterations = options?.iterations ?? DEFAULT_SECRET_ITERATIONS;\n\n // Generate a random salt for this secret's key derivation\n const saltResult = this._cryptoProvider.generateRandomBytes(MIN_SALT_LENGTH);\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (saltResult.isFailure()) {\n return fail(`Failed to generate salt: ${saltResult.message}`);\n }\n\n // Derive the key from password\n const keyResult = await this._cryptoProvider.deriveKey(password, saltResult.value, iterations);\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (keyResult.isFailure()) {\n return fail(`Key derivation failed: ${keyResult.message}`);\n }\n\n const entry: IKeyStoreSymmetricEntry = {\n name,\n type: 'encryption-key',\n key: keyResult.value,\n description: options?.description,\n createdAt: getCurrentTimestamp()\n };\n\n const warning = existing ? await this._releaseEntryResources(existing) : undefined;\n this._secrets.set(name, entry);\n this._dirty = true;\n\n return succeed({\n entry,\n replaced: existing !== undefined,\n warning,\n keyDerivation: {\n kdf: 'pbkdf2',\n salt: this._cryptoProvider.toBase64(saltResult.value),\n iterations\n }\n });\n }\n\n /**\n * Removes a secret by name. Vault-first: the in-memory vault entry is dropped\n * before any storage cleanup runs. For asymmetric-keypair entries, best-effort\n * calls {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete on the entry's\n * `id`; a failure is reported via `warning` on the result but does not roll\n * back the vault removal.\n * @param name - Name of the secret to remove\n * @returns Success with removed entry (and optional warning), Failure if not found or locked\n * @public\n */\n public async removeSecret(name: string): Promise<Result<IRemoveSecretResult>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n\n const entry = this._secrets.get(name);\n if (!entry) {\n return fail(`Secret '${name}' not found`);\n }\n\n // Vault-first: drop the in-memory entry before touching storage so a\n // storage failure cannot block removal.\n this._secrets.delete(name);\n this._dirty = true;\n\n const warning = await this._releaseEntryResources(entry);\n return succeed({ entry, warning });\n }\n\n /**\n * Imports an API key string into the vault.\n * The string is UTF-8 encoded and stored with type `'api-key'`.\n * @param name - Unique name for the secret\n * @param apiKey - The API key string\n * @param options - Optional description, whether to replace existing\n * @returns Success with entry, Failure if locked, empty, or exists and !replace\n * @public\n */\n public async importApiKey(\n name: string,\n apiKey: string,\n options?: IImportSecretOptions\n ): Promise<Result<IAddSecretResult>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n if (!name || name.length === 0) {\n return fail('Secret name cannot be empty');\n }\n if (!apiKey || apiKey.length === 0) {\n return fail('API key cannot be empty');\n }\n\n const existing = this._secrets.get(name);\n if (existing && !options?.replace) {\n return fail(`Secret '${name}' already exists - use replace=true to overwrite`);\n }\n\n const encoder = new TextEncoder();\n const entry: IKeyStoreSymmetricEntry = {\n name,\n type: 'api-key',\n key: encoder.encode(apiKey),\n description: options?.description,\n createdAt: getCurrentTimestamp()\n };\n\n const warning = existing ? await this._releaseEntryResources(existing) : undefined;\n this._secrets.set(name, entry);\n this._dirty = true;\n\n return succeed({ entry, replaced: existing !== undefined, warning });\n }\n\n /**\n * Retrieves an API key string by name.\n * Only works for secrets with type `'api-key'`.\n * @param name - Name of the secret\n * @returns Success with the API key string, Failure if not found, locked, or wrong type\n * @public\n */\n public getApiKey(name: string): Result<string> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n const entry = this._secrets.get(name);\n if (!entry) {\n return fail(`Secret '${name}' not found`);\n }\n if (entry.type !== 'api-key') {\n return fail(`Secret '${name}' is not an API key (type: ${entry.type})`);\n }\n const decoder = new TextDecoder();\n return succeed(decoder.decode(entry.key));\n }\n\n // ============================================================================\n // Asymmetric Keypair Management\n // ============================================================================\n\n /**\n * Adds a new asymmetric keypair to the vault. Storage-first: the private key\n * is stored under a freshly-minted `id` before the public-key vault entry is\n * committed. If the storage call fails, no vault entry is written and the\n * operation returns Failure.\n *\n * When `replace: true` displaces an existing entry (asymmetric or symmetric),\n * a fresh `id` is minted; the displaced entry's resources are released\n * best-effort. Failure of the storage delete is reported via `warning` on the\n * result but does not roll back the replacement.\n *\n * Requires a {@link CryptoUtils.KeyStore.IPrivateKeyStorage} backend\n * supplied at construction.\n *\n * @param name - Unique name for the entry\n * @param options - Algorithm, optional description, replace flag\n * @returns Success with the new entry, Failure if locked, no provider, or storage write failed\n * @public\n */\n public async addKeyPair(name: string, options: IAddKeyPairOptions): Promise<Result<IAddKeyPairResult>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n if (!name || name.length === 0) {\n return fail('Entry name cannot be empty');\n }\n if (!this._privateKeyStorage) {\n return fail('No private key storage configured');\n }\n\n const existing = this._secrets.get(name);\n if (existing && !options.replace) {\n return fail(`Secret '${name}' already exists - use replace=true to overwrite`);\n }\n\n // Generate the keypair before touching storage. extractable=true on backends\n // that round-trip via JWK; extractable=false on backends that hold CryptoKey\n // refs directly.\n const extractable = !this._privateKeyStorage.supportsNonExtractable;\n const keyPairResult = await this._cryptoProvider.generateKeyPair(options.algorithm, extractable);\n /* c8 ignore next 3 - crypto provider errors covered in nodeCryptoProvider tests; cannot be triggered here without mocking */\n if (keyPairResult.isFailure()) {\n return fail(`Failed to generate keypair for '${name}': ${keyPairResult.message}`);\n }\n const { publicKey, privateKey } = keyPairResult.value;\n\n const jwkResult = await this._cryptoProvider.exportPublicKeyJwk(publicKey);\n /* c8 ignore next 3 - export of an extractable freshly-generated public key is hard to fail */\n if (jwkResult.isFailure()) {\n return fail(`Failed to export public key for '${name}': ${jwkResult.message}`);\n }\n\n const idResult = this._generateId();\n /* c8 ignore next 3 - random-bytes failure is hard to trigger with a healthy provider */\n if (idResult.isFailure()) {\n return fail(`Failed to mint storage id for '${name}': ${idResult.message}`);\n }\n const id = idResult.value;\n\n // Storage-first: write the private key before committing the vault entry.\n const storeResult = await this._privateKeyStorage.store(id, privateKey);\n if (storeResult.isFailure()) {\n return fail(`Failed to persist private key for '${name}': ${storeResult.message}`);\n }\n\n const entry: IKeyStoreAsymmetricEntry = {\n name,\n type: 'asymmetric-keypair',\n id,\n algorithm: options.algorithm,\n publicKeyJwk: jwkResult.value,\n description: options.description,\n createdAt: getCurrentTimestamp()\n };\n\n const warning = existing ? await this._releaseEntryResources(existing) : undefined;\n this._secrets.set(name, entry);\n this._dirty = true;\n\n return succeed({ entry, replaced: existing !== undefined, warning });\n }\n\n /**\n * Retrieves the keypair for an asymmetric-keypair entry. The private key is\n * loaded from {@link CryptoUtils.KeyStore.IPrivateKeyStorage} on every call —\n * the keystore never caches private `CryptoKey` references between calls.\n * The public key is re-imported from the vault's JWK so callers always\n * receive a `CryptoKey` rather than the JWK form.\n * @param name - Name of the entry\n * @returns Success with `{ publicKey, privateKey }`, Failure if not found,\n * locked, wrong type, no provider, or storage load failed.\n * @public\n */\n public async getKeyPair(name: string): Promise<Result<{ publicKey: CryptoKey; privateKey: CryptoKey }>> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n const entry = this._secrets.get(name);\n if (!entry) {\n return fail(`Secret '${name}' not found`);\n }\n if (entry.type !== 'asymmetric-keypair') {\n return fail(`Secret '${name}' is not an asymmetric keypair (type: ${entry.type})`);\n }\n if (!this._privateKeyStorage) {\n return fail('No private key storage configured');\n }\n\n const privateResult = await this._privateKeyStorage.load(entry.id);\n if (privateResult.isFailure()) {\n return fail(`Failed to load private key for '${name}': ${privateResult.message}`);\n }\n\n const publicResult = await this._cryptoProvider.importPublicKeyJwk(entry.publicKeyJwk, entry.algorithm);\n /* c8 ignore next 3 - vault JWKs that previously exported cleanly are extremely unlikely to fail re-import */\n if (publicResult.isFailure()) {\n return fail(`Failed to re-import public key for '${name}': ${publicResult.message}`);\n }\n\n return succeed({ publicKey: publicResult.value, privateKey: privateResult.value });\n }\n\n /**\n * Lists secret names filtered by type.\n * @param type - The secret type to filter by\n * @returns Success with array of matching secret names, Failure if locked\n * @public\n */\n public listSecretsByType(type: KeyStoreSecretType): Result<readonly string[]> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n const names: string[] = [];\n for (const [name, entry] of this._secrets) {\n if (entry.type === type) {\n names.push(name);\n }\n }\n return succeed(names);\n }\n\n /**\n * Renames a secret.\n * @param oldName - Current name\n * @param newName - New name\n * @returns Success with updated entry, Failure if source not found, target exists, or locked\n * @public\n */\n public renameSecret(oldName: string, newName: string): Result<IKeyStoreEntry> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n if (!newName || newName.length === 0) {\n return fail('New name cannot be empty');\n }\n\n const entry = this._secrets.get(oldName);\n if (!entry) {\n return fail(`Secret '${oldName}' not found`);\n }\n\n if (oldName !== newName && this._secrets.has(newName)) {\n return fail(`Secret '${newName}' already exists`);\n }\n\n // Create new entry with new name. For asymmetric entries the spread\n // preserves `id` so the storage handle survives the rename.\n const newEntry: IKeyStoreEntry = {\n ...entry,\n name: newName\n };\n\n this._secrets.delete(oldName);\n this._secrets.set(newName, newEntry);\n this._dirty = true;\n\n return succeed(newEntry);\n }\n\n // ============================================================================\n // Persistence\n // ============================================================================\n\n /**\n * Saves the key store, returning the encrypted file content.\n * Requires the master password to encrypt.\n * @param password - The master password\n * @returns Success with IKeyStoreFile, Failure if locked\n * @public\n */\n public async save(password: string): Promise<Result<IKeyStoreFile>> {\n if (!this._secrets || !this._salt) {\n return fail('Key store is locked');\n }\n if (!password || password.length === 0) {\n return fail('Password cannot be empty');\n }\n\n // Derive the encryption key\n const keyResult = await this._cryptoProvider.deriveKey(password, this._salt, this._iterations);\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (keyResult.isFailure()) {\n return fail(`Key derivation failed: ${keyResult.message}`);\n }\n\n return this._encryptVault(keyResult.value);\n }\n\n /**\n * Saves the key store using a pre-derived key, bypassing PBKDF2 key\n * derivation. Use this when the derived key has been stored externally\n * (e.g., in another key store) and the original password is no longer\n * available.\n *\n * The supplied key must be the same key that was (or would be) derived\n * from the master password using the key store's PBKDF2 parameters.\n *\n * @param derivedKey - The pre-derived master key (32 bytes for AES-256)\n * @returns Success with IKeyStoreFile, Failure if locked or key invalid\n * @public\n */\n public async saveWithKey(derivedKey: Uint8Array): Promise<Result<IKeyStoreFile>> {\n if (!this._secrets || !this._salt) {\n return fail('Key store is locked');\n }\n if (derivedKey.length !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${derivedKey.length}`);\n }\n\n return this._encryptVault(derivedKey);\n }\n\n /**\n * Changes the master password.\n * Re-encrypts the vault with the new password-derived key.\n * @param currentPassword - Current master password (for verification)\n * @param newPassword - New master password\n * @returns Success when password changed, Failure if locked or current password incorrect\n * @public\n */\n public async changePassword(currentPassword: string, newPassword: string): Promise<Result<KeyStore>> {\n if (!this._secrets || !this._salt) {\n return fail('Key store is locked');\n }\n if (!newPassword || newPassword.length === 0) {\n return fail('New password cannot be empty');\n }\n\n // Verify current password by trying to derive and re-encrypt\n // (For opened stores, we'd need to verify against the stored file)\n if (this._keystoreFile) {\n const saltResult = this._cryptoProvider.fromBase64(this._keystoreFile.keyDerivation.salt);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (saltResult.isFailure()) {\n return fail(`Invalid salt in key store file: ${saltResult.message}`);\n }\n\n const keyResult = await this._cryptoProvider.deriveKey(\n currentPassword,\n saltResult.value,\n this._keystoreFile.keyDerivation.iterations\n );\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (keyResult.isFailure()) {\n return fail(`Key derivation failed: ${keyResult.message}`);\n }\n\n // Try to decrypt to verify password\n const ivResult = this._cryptoProvider.fromBase64(this._keystoreFile.iv);\n const authTagResult = this._cryptoProvider.fromBase64(this._keystoreFile.authTag);\n const encryptedDataResult = this._cryptoProvider.fromBase64(this._keystoreFile.encryptedData);\n\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (ivResult.isFailure() || authTagResult.isFailure() || encryptedDataResult.isFailure()) {\n return fail('Invalid key store file format');\n }\n\n const decryptResult = await this._cryptoProvider.decrypt(\n encryptedDataResult.value,\n keyResult.value,\n ivResult.value,\n authTagResult.value\n );\n if (decryptResult.isFailure()) {\n return fail('Current password is incorrect');\n }\n }\n\n // Generate new salt for the new password using crypto provider\n const saltResult = this._cryptoProvider.generateRandomBytes(MIN_SALT_LENGTH);\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (saltResult.isFailure()) {\n return fail(`Failed to generate salt: ${saltResult.message}`);\n }\n\n this._salt = saltResult.value;\n this._dirty = true;\n\n // Save with new password\n const saveResult = await this.save(newPassword);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (saveResult.isFailure()) {\n return fail(saveResult.message);\n }\n return succeed(this);\n }\n\n // ============================================================================\n // IEncryptionProvider\n // ============================================================================\n\n /** {@inheritDoc IEncryptionProvider.encryptByName} */\n public async encryptByName<TMetadata = JsonValue>(\n secretName: string,\n content: JsonValue,\n metadata?: TMetadata\n ): Promise<Result<IEncryptedFile<TMetadata>>> {\n const secretResult = this.getSecret(secretName);\n if (secretResult.isFailure()) {\n return fail(`encryptByName: ${secretResult.message}`);\n }\n if (secretResult.value.type === 'asymmetric-keypair') {\n return fail(\n `encryptByName: secret '${secretName}' is an asymmetric keypair, not symmetric key material`\n );\n }\n\n return createEncryptedFile({\n content,\n secretName,\n key: secretResult.value.key,\n cryptoProvider: this._cryptoProvider,\n metadata\n });\n }\n\n // ============================================================================\n // Integration with IEncryptionConfig\n // ============================================================================\n\n /**\n * Creates a SecretProvider function for use with IEncryptionConfig.\n * The returned function looks up secrets from this key store.\n * @returns Success with SecretProvider, Failure if locked\n * @public\n */\n public getSecretProvider(): Result<SecretProvider> {\n if (!this._secrets) {\n return fail('Key store is locked');\n }\n\n const secrets = this._secrets;\n const provider: SecretProvider = async (secretName: string): Promise<Result<Uint8Array>> => {\n const entry = secrets.get(secretName);\n if (!entry) {\n return fail(`Secret '${secretName}' not found in key store`);\n }\n if (entry.type === 'asymmetric-keypair') {\n return fail(`Secret '${secretName}' is an asymmetric keypair, not symmetric key material`);\n }\n return succeed(entry.key);\n };\n\n return succeed(provider);\n }\n\n /**\n * Creates a partial IEncryptionConfig using this key store as the secret source.\n * @returns Partial config that can be spread into a full IEncryptionConfig\n * @public\n */\n public getEncryptionConfig(): Result<Pick<IEncryptionConfig, 'secretProvider' | 'cryptoProvider'>> {\n const providerResult = this.getSecretProvider();\n if (providerResult.isFailure()) {\n return fail(providerResult.message);\n }\n\n return succeed({\n secretProvider: providerResult.value,\n cryptoProvider: this._cryptoProvider\n });\n }\n\n // ============================================================================\n // Private: Vault Encryption / Decryption\n // ============================================================================\n\n /**\n * Encrypts the vault with a derived key and returns the key store file.\n * Shared by `save()` and `saveWithKey()`.\n */\n private async _encryptVault(derivedKey: Uint8Array): Promise<Result<IKeyStoreFile>> {\n // _secrets and _salt are guaranteed non-undefined by callers\n const secrets = this._secrets!;\n const salt = this._salt!;\n\n // Build vault contents\n const secretEntries: Record<string, IKeyStoreEntryJson> = {};\n for (const [name, entry] of secrets) {\n if (entry.type === 'asymmetric-keypair') {\n secretEntries[name] = {\n name: entry.name,\n type: entry.type,\n id: entry.id,\n algorithm: entry.algorithm,\n publicKeyJwk: entry.publicKeyJwk,\n description: entry.description,\n createdAt: entry.createdAt\n };\n } else {\n secretEntries[name] = {\n name: entry.name,\n type: entry.type,\n key: this._cryptoProvider.toBase64(entry.key),\n description: entry.description,\n createdAt: entry.createdAt\n };\n }\n }\n\n const vaultContents: IKeyStoreVaultContents = {\n version: KEYSTORE_FORMAT,\n secrets: secretEntries\n };\n\n // Serialize and encrypt\n const jsonResult = captureResult(() => JSON.stringify(vaultContents));\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (jsonResult.isFailure()) {\n return fail(`Failed to serialize vault: ${jsonResult.message}`);\n }\n\n const encryptResult = await this._cryptoProvider.encrypt(jsonResult.value, derivedKey);\n /* c8 ignore next 3 - crypto provider errors tested but coverage intermittently missed */\n if (encryptResult.isFailure()) {\n return fail(`Encryption failed: ${encryptResult.message}`);\n }\n\n const { iv, authTag, encryptedData } = encryptResult.value;\n\n const keystoreFileData: IKeyStoreFile = {\n format: KEYSTORE_FORMAT,\n algorithm: Constants.DEFAULT_ALGORITHM,\n iv: this._cryptoProvider.toBase64(iv),\n authTag: this._cryptoProvider.toBase64(authTag),\n encryptedData: this._cryptoProvider.toBase64(encryptedData),\n keyDerivation: {\n kdf: 'pbkdf2',\n salt: this._cryptoProvider.toBase64(salt),\n iterations: this._iterations\n }\n };\n\n this._keystoreFile = keystoreFileData;\n this._dirty = false;\n this._isNew = false;\n\n return succeed(keystoreFileData);\n }\n\n /**\n * Decrypts the vault with a derived key and loads secrets into memory.\n * Shared by `unlock()` and `unlockWithKey()`.\n */\n private async _decryptVault(derivedKey: Uint8Array): Promise<Result<KeyStore>> {\n const keystoreFile = this._keystoreFile;\n if (keystoreFile === undefined) {\n return fail('No key store file loaded');\n }\n\n const ivResult = this._cryptoProvider.fromBase64(keystoreFile.iv);\n const authTagResult = this._cryptoProvider.fromBase64(keystoreFile.authTag);\n const encryptedDataResult = this._cryptoProvider.fromBase64(keystoreFile.encryptedData);\n\n /* c8 ignore next 9 - base64 decode errors tested but coverage intermittently missed */\n if (ivResult.isFailure()) {\n return fail(`Invalid IV in key store file: ${ivResult.message}`);\n }\n if (authTagResult.isFailure()) {\n return fail(`Invalid auth tag in key store file: ${authTagResult.message}`);\n }\n if (encryptedDataResult.isFailure()) {\n return fail(`Invalid encrypted data in key store file: ${encryptedDataResult.message}`);\n }\n\n const decryptResult = await this._cryptoProvider.decrypt(\n encryptedDataResult.value,\n derivedKey,\n ivResult.value,\n authTagResult.value\n );\n if (decryptResult.isFailure()) {\n return fail('Incorrect password or corrupted key store');\n }\n\n // Parse the vault contents\n const parseResult = captureResult(() => JSON.parse(decryptResult.value) as unknown);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (parseResult.isFailure()) {\n return fail(`Failed to parse vault contents: ${parseResult.message}`);\n }\n\n const vaultResult = keystoreVaultContents.convert(parseResult.value);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (vaultResult.isFailure()) {\n return fail(`Invalid vault format: ${vaultResult.message}`);\n }\n\n // Build secrets into local variables to avoid partial state on failure\n const saltResult = this._cryptoProvider.fromBase64(keystoreFile.keyDerivation.salt);\n if (saltResult.isFailure()) {\n return fail(`Invalid salt in key store file: ${saltResult.message}`);\n }\n const secrets = new Map<string, IKeyStoreEntry>();\n for (const [name, jsonEntry] of Object.entries(vaultResult.value.secrets)) {\n if (jsonEntry.type === 'asymmetric-keypair') {\n const entry: IKeyStoreAsymmetricEntry = {\n name,\n type: jsonEntry.type,\n id: jsonEntry.id,\n algorithm: jsonEntry.algorithm,\n publicKeyJwk: jsonEntry.publicKeyJwk,\n description: jsonEntry.description,\n createdAt: jsonEntry.createdAt\n };\n secrets.set(name, entry);\n } else {\n const keyBytesResult = this._cryptoProvider.fromBase64(jsonEntry.key);\n /* c8 ignore next 3 - error path tested but coverage intermittently missed */\n if (keyBytesResult.isFailure()) {\n return fail(`Invalid key for secret '${name}': ${keyBytesResult.message}`);\n }\n const entry: IKeyStoreSymmetricEntry = {\n name,\n type: jsonEntry.type,\n key: keyBytesResult.value,\n description: jsonEntry.description,\n createdAt: jsonEntry.createdAt\n };\n secrets.set(name, entry);\n }\n }\n\n // All validation passed — commit state atomically\n this._salt = saltResult.value;\n this._secrets = secrets;\n this._state = 'unlocked';\n this._dirty = false;\n\n return succeed(this);\n }\n\n // ============================================================================\n // Private: Helpers for asymmetric flows\n // ============================================================================\n\n /**\n * Releases the resources held by an entry being displaced from the vault.\n * Symmetric entries get their key buffer zeroed in place. Asymmetric entries\n * have their private-key blob best-effort deleted from\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}; if the storage call fails,\n * a warning string is returned but the displacement still proceeds — the\n * orphaned blob is left for consumer-side GC. Without a configured provider,\n * asymmetric cleanup is silently skipped.\n * @returns A warning string if storage cleanup failed, otherwise undefined.\n */\n private async _releaseEntryResources(entry: IKeyStoreEntry): Promise<string | undefined> {\n if (entry.type === 'asymmetric-keypair') {\n if (!this._privateKeyStorage) {\n return undefined;\n }\n const deleteResult = await this._privateKeyStorage.delete(entry.id);\n if (deleteResult.isFailure()) {\n return `Failed to delete prior storage blob for '${entry.name}' (id ${entry.id}): ${deleteResult.message}`;\n }\n return undefined;\n }\n entry.key.fill(0);\n return undefined;\n }\n\n /**\n * Mints a fresh UUID v4 storage handle using the crypto provider's\n * {@link CryptoUtils.ICryptoProvider.generateRandomBytes | generateRandomBytes}.\n * Random-bytes failures propagate as Failure.\n */\n private _generateId(): Result<string> {\n return this._cryptoProvider.generateRandomBytes(16).onSuccess((bytes) => {\n // Per RFC 4122 §4.4: set version (4) and variant (10xx) bits.\n // eslint-disable-next-line no-bitwise\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n // eslint-disable-next-line no-bitwise\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n return succeed(\n `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(\n 20,\n 32\n )}`\n );\n });\n }\n}\n"]}
@@ -17,6 +17,9 @@
17
17
  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
+ // Re-export so consumers can continue to access the algorithm enum via the
21
+ // CryptoUtils.KeyStore namespace alongside the rest of the keystore types.
22
+ export { allKeyPairAlgorithms } from '../model';
20
23
  /**
21
24
  * Current format version constant.
22
25
  * @public
@@ -33,11 +36,29 @@ export const DEFAULT_KEYSTORE_ITERATIONS = 600000;
33
36
  * @public
34
37
  */
35
38
  export const MIN_SALT_LENGTH = 16;
39
+ /**
40
+ * All valid symmetric secret types.
41
+ * @public
42
+ */
43
+ export const allKeyStoreSymmetricSecretTypes = [
44
+ 'encryption-key',
45
+ 'api-key'
46
+ ];
47
+ /**
48
+ * All valid asymmetric secret types.
49
+ * @public
50
+ */
51
+ export const allKeyStoreAsymmetricSecretTypes = [
52
+ 'asymmetric-keypair'
53
+ ];
36
54
  /**
37
55
  * All valid key store secret types.
38
56
  * @public
39
57
  */
40
- export const allKeyStoreSecretTypes = ['encryption-key', 'api-key'];
58
+ export const allKeyStoreSecretTypes = [
59
+ ...allKeyStoreAsymmetricSecretTypes,
60
+ ...allKeyStoreSymmetricSecretTypes
61
+ ];
41
62
  /**
42
63
  * Default PBKDF2 iterations for secret-level key derivation.
43
64
  * Lower than keystore encryption since these are used more frequently.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/model.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAKZ,2EAA2E;AAC3E,2EAA2E;AAC3E,OAAO,EAAE,oBAAoB,EAAoB,MAAM,UAAU,CAAC;AAYlE;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAmB,aAAa,CAAC;AAE7D;;;;GAIG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAW,MAAM,CAAC;AAE1D;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAW,EAAE,CAAC;AAc1C;;;GAGG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAA+C;IACzF,gBAAgB;IAChB,SAAS;CACV,CAAC;AAWF;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAgD;IAC3F,oBAAoB;CACrB,CAAC;AAQF;;;GAGG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAsC;IACvE,GAAG,gCAAgC;IACnC,GAAG,+BAA+B;CACnC,CAAC;AAsYF;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAW,MAAM,CAAC;AAoFxD,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,IAAa;IAC1C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,IAA+B,CAAC;IAC5C,OAAO,GAAG,CAAC,MAAM,KAAK,eAAe,CAAC;AACxC,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { EncryptionAlgorithm, ICryptoProvider, IKeyDerivationParams, KeyPairAlgorithm } from '../model';\nimport { IPrivateKeyStorage } from './privateKeyStorage';\n\n// Re-export so consumers can continue to access the algorithm enum via the\n// CryptoUtils.KeyStore namespace alongside the rest of the keystore types.\nexport { allKeyPairAlgorithms, KeyPairAlgorithm } from '../model';\n\n// ============================================================================\n// Key Store Format Types\n// ============================================================================\n\n/**\n * Format version for key store files.\n * @public\n */\nexport type KeyStoreFormat = 'keystore-v1';\n\n/**\n * Current format version constant.\n * @public\n */\nexport const KEYSTORE_FORMAT: KeyStoreFormat = 'keystore-v1';\n\n/**\n * Default PBKDF2 iterations for key store encryption.\n * Higher than regular files since this protects the master key vault.\n * @public\n */\nexport const DEFAULT_KEYSTORE_ITERATIONS: number = 600000;\n\n/**\n * Minimum salt length for key derivation.\n * @public\n */\nexport const MIN_SALT_LENGTH: number = 16;\n\n// ============================================================================\n// Key Store Vault Contents (Decrypted State)\n// ============================================================================\n\n/**\n * Discriminator for symmetric secret types stored in the vault.\n * - `'encryption-key'`: A 32-byte AES-256 encryption key.\n * - `'api-key'`: An arbitrary-length API key string (UTF-8 encoded).\n * @public\n */\nexport type KeyStoreSymmetricSecretType = 'encryption-key' | 'api-key';\n\n/**\n * All valid symmetric secret types.\n * @public\n */\nexport const allKeyStoreSymmetricSecretTypes: ReadonlyArray<KeyStoreSymmetricSecretType> = [\n 'encryption-key',\n 'api-key'\n];\n\n/**\n * Discriminator for asymmetric secret types stored in the vault.\n * - `'asymmetric-keypair'`: A public/private key pair. The public key is held in\n * the vault as a JWK; the private key lives in the supplied\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider.\n * @public\n */\nexport type KeyStoreAsymmetricSecretType = 'asymmetric-keypair';\n\n/**\n * All valid asymmetric secret types.\n * @public\n */\nexport const allKeyStoreAsymmetricSecretTypes: ReadonlyArray<KeyStoreAsymmetricSecretType> = [\n 'asymmetric-keypair'\n];\n\n/**\n * Discriminator for any secret type stored in the vault.\n * @public\n */\nexport type KeyStoreSecretType = KeyStoreSymmetricSecretType | KeyStoreAsymmetricSecretType;\n\n/**\n * All valid key store secret types.\n * @public\n */\nexport const allKeyStoreSecretTypes: ReadonlyArray<KeyStoreSecretType> = [\n ...allKeyStoreAsymmetricSecretTypes,\n ...allKeyStoreSymmetricSecretTypes\n];\n\n/**\n * A symmetric secret entry stored in the vault (in-memory representation).\n * Holds the raw key material directly — for `'encryption-key'` it is a 32-byte\n * AES-256 key; for `'api-key'` it is the UTF-8 encoded API key string.\n * @public\n */\nexport interface IKeyStoreSymmetricEntry {\n /**\n * Unique name for this secret (used as lookup key).\n */\n readonly name: string;\n\n /**\n * Symmetric secret type discriminator.\n */\n readonly type: KeyStoreSymmetricSecretType;\n\n /**\n * The secret data.\n * - For `'encryption-key'`: 32-byte AES-256 key.\n * - For `'api-key'`: UTF-8 encoded API key string (arbitrary length).\n */\n readonly key: Uint8Array;\n\n /**\n * Optional description for this secret.\n */\n readonly description?: string;\n\n /**\n * When this secret was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * An asymmetric keypair entry stored in the vault (in-memory representation).\n * Holds only the public key (as a JWK) and a stable handle (`id`) the\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider uses to fetch the private key.\n * @public\n */\nexport interface IKeyStoreAsymmetricEntry {\n /**\n * Unique name for this entry (used as vault lookup key, renameable).\n */\n readonly name: string;\n\n /**\n * Asymmetric secret type discriminator.\n */\n readonly type: KeyStoreAsymmetricSecretType;\n\n /**\n * Immutable handle used by {@link CryptoUtils.KeyStore.IPrivateKeyStorage} to address the\n * private key. Independent of `name`; survives renames.\n */\n readonly id: string;\n\n /**\n * Algorithm used to generate this keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * The public key as a JSON Web Key.\n */\n readonly publicKeyJwk: JsonWebKey;\n\n /**\n * Optional description for this entry.\n */\n readonly description?: string;\n\n /**\n * When this entry was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * Any vault entry, discriminated by `type`.\n * @public\n */\nexport type IKeyStoreEntry = IKeyStoreSymmetricEntry | IKeyStoreAsymmetricEntry;\n\n/**\n * Backwards-compatible alias for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntry}.\n * @deprecated Use {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntry} for symmetric\n * entries or {@link CryptoUtils.KeyStore.IKeyStoreEntry} for the discriminated union.\n * @public\n */\nexport type IKeyStoreSecretEntry = IKeyStoreSymmetricEntry;\n\n/**\n * JSON-serializable representation of a symmetric secret entry.\n *\n * @remarks\n * Describes the *normalized* shape after parsing. `type` is required here\n * because the converter (see\n * {@link CryptoUtils.KeyStore.Converters.keystoreSymmetricEntryJson | keystoreSymmetricEntryJson})\n * injects the default `'encryption-key'` when reading vaults written before\n * asymmetric-keypair support added the discriminator. Raw on-wire bytes from\n * a legacy vault may therefore omit `type`; downstream code only ever sees\n * the post-conversion shape declared here.\n *\n * @public\n */\nexport interface IKeyStoreSymmetricEntryJson {\n /**\n * Unique name for this secret.\n */\n readonly name: string;\n\n /**\n * Symmetric secret type discriminator.\n *\n * Required on this normalized model type. Vaults written prior to the\n * asymmetric-keypair support may omit this field on the wire; the\n * converter injects `'encryption-key'` when missing for backwards\n * compatibility, so by the time a value of this type is observed the\n * discriminator is always present.\n */\n readonly type: KeyStoreSymmetricSecretType;\n\n /**\n * Base64-encoded secret data.\n */\n readonly key: string;\n\n /**\n * Optional description.\n */\n readonly description?: string;\n\n /**\n * When this secret was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * JSON-serializable representation of an asymmetric keypair entry.\n * The private key is not present here — it lives in the\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage} provider, addressed by `id`.\n * @public\n */\nexport interface IKeyStoreAsymmetricEntryJson {\n /**\n * Unique name for this entry.\n */\n readonly name: string;\n\n /**\n * Asymmetric secret type discriminator.\n */\n readonly type: KeyStoreAsymmetricSecretType;\n\n /**\n * Immutable handle used by {@link CryptoUtils.KeyStore.IPrivateKeyStorage} to address the\n * private key.\n */\n readonly id: string;\n\n /**\n * Algorithm used to generate this keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * The public key as a JSON Web Key.\n */\n readonly publicKeyJwk: JsonWebKey;\n\n /**\n * Optional description.\n */\n readonly description?: string;\n\n /**\n * When this entry was added (ISO 8601).\n */\n readonly createdAt: string;\n}\n\n/**\n * Any JSON vault entry, discriminated by `type`.\n * @public\n */\nexport type IKeyStoreEntryJson = IKeyStoreSymmetricEntryJson | IKeyStoreAsymmetricEntryJson;\n\n/**\n * Backwards-compatible alias for {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson}.\n * @deprecated Use {@link CryptoUtils.KeyStore.IKeyStoreSymmetricEntryJson} for\n * symmetric entries or {@link CryptoUtils.KeyStore.IKeyStoreEntryJson} for the\n * discriminated union.\n * @public\n */\nexport type IKeyStoreSecretEntryJson = IKeyStoreSymmetricEntryJson;\n\n/**\n * The decrypted vault contents - a versioned map of entries.\n * @public\n */\nexport interface IKeyStoreVaultContents {\n /**\n * Format version for vault contents.\n */\n readonly version: KeyStoreFormat;\n\n /**\n * Map of entry name to entry (symmetric or asymmetric).\n */\n readonly secrets: Record<string, IKeyStoreEntryJson>;\n}\n\n// ============================================================================\n// Key Store File Format (Encrypted State)\n// ============================================================================\n\n/**\n * The encrypted key store file format.\n * @public\n */\nexport interface IKeyStoreFile {\n /**\n * Format identifier.\n */\n readonly format: KeyStoreFormat;\n\n /**\n * Algorithm used for encryption.\n */\n readonly algorithm: EncryptionAlgorithm;\n\n /**\n * Base64-encoded initialization vector.\n */\n readonly iv: string;\n\n /**\n * Base64-encoded authentication tag.\n */\n readonly authTag: string;\n\n /**\n * Base64-encoded encrypted vault contents.\n */\n readonly encryptedData: string;\n\n /**\n * Key derivation parameters (required for key store - always password-derived).\n */\n readonly keyDerivation: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Key Store State and Configuration\n// ============================================================================\n\n/**\n * Key store lock state.\n * @public\n */\nexport type KeyStoreLockState = 'locked' | 'unlocked';\n\n/**\n * Parameters for creating a new key store.\n * @public\n */\nexport interface IKeyStoreCreateParams {\n /**\n * Crypto provider to use.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * PBKDF2 iterations (defaults to DEFAULT_KEYSTORE_ITERATIONS).\n */\n readonly iterations?: number;\n\n /**\n * Optional private-key storage backend. Required to use `addKeyPair` /\n * `getKeyPair`; absent backends still permit opening, listing, and reading\n * public-key metadata for asymmetric entries.\n */\n readonly privateKeyStorage?: IPrivateKeyStorage;\n}\n\n/**\n * Parameters for opening an existing key store.\n * @public\n */\nexport interface IKeyStoreOpenParams {\n /**\n * Crypto provider to use.\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * The encrypted key store file content.\n */\n readonly keystoreFile: IKeyStoreFile;\n\n /**\n * Optional private-key storage backend. Required to use `addKeyPair` /\n * `getKeyPair`; absent backends still permit opening, listing, and reading\n * public-key metadata for asymmetric entries.\n */\n readonly privateKeyStorage?: IPrivateKeyStorage;\n}\n\n/**\n * Result of adding a secret to the key store.\n * @public\n */\nexport interface IAddSecretResult {\n /**\n * The secret entry that was added.\n */\n readonly entry: IKeyStoreSymmetricEntry;\n\n /**\n * Whether this replaced an existing secret.\n */\n readonly replaced: boolean;\n\n /**\n * Best-effort warning from displaced-resource cleanup. Set when this call\n * replaced an asymmetric-keypair entry but the corresponding\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete failed; the new\n * entry is still committed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n/**\n * Options for adding a secret.\n * @public\n */\nexport interface IAddSecretOptions {\n /**\n * Optional description for the secret.\n */\n readonly description?: string;\n}\n\n/**\n * Options for importing a secret.\n * @public\n */\nexport interface IImportSecretOptions extends IAddSecretOptions {\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n}\n\n/**\n * Options for importing raw key material via {@link KeyStore.importSecret}.\n * Extends {@link IImportSecretOptions} with a type classification.\n * @public\n */\nexport interface IImportKeyOptions extends IImportSecretOptions {\n /**\n * Symmetric secret type classification for the imported key material.\n * @defaultValue 'encryption-key'\n */\n readonly type?: KeyStoreSymmetricSecretType;\n}\n\n/**\n * Options for adding a secret derived from a password.\n * @public\n */\nexport interface IAddSecretFromPasswordOptions extends IAddSecretOptions {\n /**\n * Whether to replace an existing secret with the same name.\n */\n readonly replace?: boolean;\n\n /**\n * PBKDF2 iterations for key derivation.\n * @defaultValue DEFAULT_SECRET_ITERATIONS (350000)\n */\n readonly iterations?: number;\n}\n\n/**\n * Default PBKDF2 iterations for secret-level key derivation.\n * Lower than keystore encryption since these are used more frequently.\n * @public\n */\nexport const DEFAULT_SECRET_ITERATIONS: number = 350000;\n\n/**\n * Result of adding a password-derived secret.\n * Extends {@link IAddSecretResult} with key derivation parameters\n * needed to store alongside encrypted files.\n * @public\n */\nexport interface IAddSecretFromPasswordResult extends IAddSecretResult {\n /**\n * Key derivation parameters used to derive the secret key.\n * Store these in encrypted file metadata so the password alone\n * can re-derive the same key for decryption.\n */\n readonly keyDerivation: IKeyDerivationParams;\n}\n\n/**\n * Options for adding an asymmetric keypair to the key store.\n * @public\n */\nexport interface IAddKeyPairOptions {\n /**\n * Algorithm to use for the new keypair.\n */\n readonly algorithm: KeyPairAlgorithm;\n\n /**\n * Optional description for the entry.\n */\n readonly description?: string;\n\n /**\n * Whether to replace an existing entry with the same name.\n * Replacement mints a fresh storage `id` and best-effort deletes the\n * displaced storage blob; see the keystore design doc for details.\n */\n readonly replace?: boolean;\n}\n\n/**\n * Result of adding an asymmetric keypair to the key store.\n * @public\n */\nexport interface IAddKeyPairResult {\n /**\n * The asymmetric entry that was added.\n */\n readonly entry: IKeyStoreAsymmetricEntry;\n\n /**\n * Whether this replaced an existing entry.\n */\n readonly replaced: boolean;\n\n /**\n * Best-effort warning from displaced-resource cleanup. Set when this call\n * replaced a prior entry but the corresponding\n * {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete failed; the new\n * keypair is still committed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n/**\n * Result of removing a secret from the key store.\n * @public\n */\nexport interface IRemoveSecretResult {\n /**\n * The secret entry that was removed from the vault.\n */\n readonly entry: IKeyStoreEntry;\n\n /**\n * Best-effort warning from {@link CryptoUtils.KeyStore.IPrivateKeyStorage}.delete\n * for asymmetric entries when the storage call failed. The vault entry is\n * still considered removed and the orphaned blob is left for consumer-side\n * GC to reconcile.\n */\n readonly warning?: string;\n}\n\n// ============================================================================\n// Detection Helper\n// ============================================================================\n\n/**\n * Checks if a JSON object appears to be a key store file.\n * Uses the format field as a discriminator.\n * @param json - JSON object to check\n * @returns true if the object has the key store format field\n * @public\n */\nexport function isKeyStoreFile(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) {\n return false;\n }\n const obj = json as Record<string, unknown>;\n return obj.format === KEYSTORE_FORMAT;\n}\n"]}
@@ -0,0 +1,21 @@
1
+ // Copyright (c) 2026 Erik Fortune
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ // of this software and associated documentation files (the "Software"), to deal
5
+ // in the Software without restriction, including without limitation the rights
6
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ // copies of the Software, and to permit persons to whom the Software is
8
+ // furnished to do so, subject to the following conditions:
9
+ //
10
+ // The above copyright notice and this permission notice shall be included in all
11
+ // copies or substantial portions of the Software.
12
+ //
13
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ // SOFTWARE.
20
+ export {};
21
+ //# sourceMappingURL=privateKeyStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"privateKeyStorage.js","sourceRoot":"","sources":["../../../../src/packlets/crypto-utils/keystore/privateKeyStorage.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { Result } from '@fgv/ts-utils';\n\n/**\n * Pluggable backend that persists raw asymmetric private keys outside of the\n * encrypted keystore vault. Concrete implementations live in platform-specific\n * packages (e.g. an IndexedDB-backed implementation in `@fgv/ts-web-extras` or\n * an encrypted-file implementation in `@fgv/ts-chocolate`).\n *\n * The keystore writes storage-first: a private key is always stored here\n * before the corresponding public-key vault entry is committed. Conversely,\n * deletes hit the vault first and then this storage best-effort. As a result,\n * crashes or skipped saves can leave orphaned blobs here; callers are expected\n * to reconcile via {@link CryptoUtils.KeyStore.IPrivateKeyStorage.list} cross-referenced\n * against the keystore's asymmetric entries.\n *\n * @public\n */\nexport interface IPrivateKeyStorage {\n /**\n * Whether keys generated for this backend may be marked\n * `extractable: false`. `true` on backends that store `CryptoKey`\n * objects directly (e.g. IndexedDB). `false` on backends that must\n * round-trip via JWK (e.g. encrypted-file backends).\n */\n readonly supportsNonExtractable: boolean;\n\n /**\n * Stores `key` under `id`. Returns the stored `id` on success so the\n * call can compose into a Result chain.\n * @param id - Storage handle to write under.\n * @param key - The private `CryptoKey` to persist.\n */\n store(id: string, key: CryptoKey): Promise<Result<string>>;\n\n /**\n * Loads the private key previously stored under `id`.\n * @param id - Storage handle to look up.\n */\n load(id: string): Promise<Result<CryptoKey>>;\n\n /**\n * Deletes the entry stored under `id`. Returns the deleted `id` on\n * success so the call can compose into a Result chain.\n * @param id - Storage handle to remove.\n */\n delete(id: string): Promise<Result<string>>;\n\n /**\n * Lists every `id` currently held by the backend. Used by consumers to\n * garbage-collect orphans left by crashes or aborted sessions; the\n * keystore itself does not invoke this automatically.\n */\n list(): Promise<Result<readonly string[]>>;\n}\n"]}
@@ -19,6 +19,15 @@
19
19
  // SOFTWARE.
20
20
  import * as Constants from './constants';
21
21
  export { Constants };
22
+ /**
23
+ * All valid key pair algorithms.
24
+ * @public
25
+ */
26
+ export const allKeyPairAlgorithms = [
27
+ 'ecdsa-p256',
28
+ 'rsa-oaep-2048',
29
+ 'ecdh-p256'
30
+ ];
22
31
  // ============================================================================
23
32
  // Detection Helper
24
33
  // ============================================================================
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/model.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAKZ,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,CAAC;AA2HrB;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAoC;IACnE,YAAY;IACZ,eAAe;IACf,WAAW;CACZ,CAAC;AAyUF,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,IAAa;IAC3C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;QAC9C,OAAO,KAAK,CAAC;IACf,CAAC;IACD,MAAM,GAAG,GAAG,IAA+B,CAAC;IAC5C,OAAO,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,qBAAqB,CAAC;AACxD,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport { JsonValue } from '@fgv/ts-json-base';\nimport { Result } from '@fgv/ts-utils';\n\nimport * as Constants from './constants';\nexport { Constants };\n\n// ============================================================================\n// Encryption Types\n// ============================================================================\n\n/**\n * Supported encryption algorithms.\n * @public\n */\nexport type EncryptionAlgorithm = typeof Constants.DEFAULT_ALGORITHM;\n\n/**\n * Format version for encrypted files.\n * @public\n */\nexport type EncryptedFileFormat = typeof Constants.ENCRYPTED_FILE_FORMAT;\n\n/**\n * Named secret for encryption/decryption.\n * @public\n */\nexport interface INamedSecret {\n /**\n * Unique name for this secret (referenced in encrypted files).\n */\n readonly name: string;\n\n /**\n * The actual secret key (32 bytes for AES-256).\n */\n readonly key: Uint8Array;\n}\n\n/**\n * Result of an encryption operation.\n * @public\n */\nexport interface IEncryptionResult {\n /**\n * Initialization vector used for encryption (12 bytes for GCM).\n */\n readonly iv: Uint8Array;\n\n /**\n * Authentication tag from GCM mode (16 bytes).\n */\n readonly authTag: Uint8Array;\n\n /**\n * The encrypted data.\n */\n readonly encryptedData: Uint8Array;\n}\n\n/**\n * Asymmetric keypair algorithms supported by the crypto provider.\n * - `'ecdsa-p256'`: ECDSA over the P-256 curve, for signing.\n * - `'rsa-oaep-2048'`: RSA-OAEP, 2048-bit modulus with SHA-256, for encryption.\n * - `'ecdh-p256'`: ECDH over the P-256 curve, for key agreement\n * (e.g. as the recipient keypair in\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} /\n * {@link CryptoUtils.ICryptoProvider.unwrapBytes | unwrapBytes}).\n * @public\n */\nexport type KeyPairAlgorithm = 'ecdsa-p256' | 'rsa-oaep-2048' | 'ecdh-p256';\n\n/**\n * Caller-supplied HKDF parameters that domain-separate one\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes} call from another.\n * Two wraps that share recipient but differ on `salt` or `info` derive distinct\n * wrap keys, so callers should pick values that bind the wrap to its\n * application context (e.g. a content hash for `salt` and a secret name for\n * `info`).\n *\n * Both fields are required; pass an empty `Uint8Array` if the caller has no\n * value to bind on a given axis. Silent defaulting would hide protocol\n * mistakes, so the API does not pick defaults.\n * @public\n */\nexport interface IWrapBytesOptions {\n /**\n * HKDF salt. Domain-separates this wrap from others in different contexts.\n * Caller picks; common choices include a content hash, document id, channel\n * id, etc.\n */\n readonly salt: Uint8Array;\n\n /**\n * HKDF info. Further binds the derived key to a specific use within the\n * calling application. Caller picks; common choices include a secret name,\n * message type, or version tag.\n */\n readonly info: Uint8Array;\n}\n\n/**\n * Output of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}. The\n * shape is JSON-serializable so it can travel directly over the wire or be\n * persisted as-is.\n * @public\n */\nexport interface IWrappedBytes {\n /**\n * Sender's ephemeral ECDH P-256 public key as a JSON Web Key. The matching\n * ephemeral private key is dropped after the shared-secret derive.\n */\n readonly ephemeralPublicKey: JsonWebKey;\n\n /**\n * AES-GCM nonce, base64-encoded. 12 bytes (96 bits) — the standard AES-GCM\n * nonce length.\n */\n readonly nonce: string;\n\n /**\n * AES-GCM ciphertext concatenated with the 16-byte authentication tag,\n * base64-encoded. Tampering with either the nonce or the ciphertext causes\n * unwrap to fail GCM authentication.\n */\n readonly ciphertext: string;\n}\n\n/**\n * All valid key pair algorithms.\n * @public\n */\nexport const allKeyPairAlgorithms: ReadonlyArray<KeyPairAlgorithm> = [\n 'ecdsa-p256',\n 'rsa-oaep-2048',\n 'ecdh-p256'\n];\n\n/**\n * Supported key derivation functions.\n * @public\n */\nexport type KeyDerivationFunction = 'pbkdf2';\n\n/**\n * Key derivation parameters stored in encrypted files.\n * Allows decryption with password without needing to know the original salt/iterations.\n * @public\n */\nexport interface IKeyDerivationParams {\n /**\n * Key derivation function used.\n */\n readonly kdf: KeyDerivationFunction;\n\n /**\n * Base64-encoded salt used for key derivation.\n */\n readonly salt: string;\n\n /**\n * Number of iterations used for key derivation.\n */\n readonly iterations: number;\n}\n\n/**\n * Generic encrypted file format.\n * This is the JSON structure stored in encrypted files.\n * @typeParam TMetadata - Type of optional unencrypted metadata\n * @public\n */\nexport interface IEncryptedFile<TMetadata = JsonValue> {\n /**\n * Format identifier for versioning.\n */\n readonly format: EncryptedFileFormat;\n\n /**\n * Name of the secret required to decrypt (references INamedSecret.name).\n */\n readonly secretName: string;\n\n /**\n * Algorithm used for encryption.\n */\n readonly algorithm: EncryptionAlgorithm;\n\n /**\n * Base64-encoded initialization vector.\n */\n readonly iv: string;\n\n /**\n * Base64-encoded authentication tag (for GCM mode).\n */\n readonly authTag: string;\n\n /**\n * Base64-encoded encrypted data (JSON string when decrypted).\n */\n readonly encryptedData: string;\n\n /**\n * Optional unencrypted metadata for display/filtering.\n */\n readonly metadata?: TMetadata;\n\n /**\n * Optional key derivation parameters.\n * If present, allows decryption using a password with these parameters.\n * If absent, a pre-derived key must be provided.\n */\n readonly keyDerivation?: IKeyDerivationParams;\n}\n\n// ============================================================================\n// Crypto Provider Interface\n// ============================================================================\n\n/**\n * Crypto provider interface for cross-platform encryption.\n * Implementations provided for Node.js (crypto module) and browser (Web Crypto API).\n * @public\n */\nexport interface ICryptoProvider {\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns Success with encryption result, or Failure with error\n */\n encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>>;\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns Success with decrypted UTF-8 string, or Failure with error\n */\n decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>>;\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns Success with generated key, or Failure with error\n */\n generateKey(): Promise<Result<Uint8Array>>;\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns Success with derived 32-byte key, or Failure with error\n */\n deriveKey(password: string, salt: Uint8Array, iterations: number): Promise<Result<Uint8Array>>;\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns Success with hex-encoded hash string, or Failure with error\n */\n sha256(data: string): Promise<Result<string>>;\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n generateRandomBytes(length: number): Result<Uint8Array>;\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n toBase64(data: Uint8Array): string;\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n fromBase64(base64: string): Result<Uint8Array>;\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair for the requested algorithm.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.\n * @param extractable - Whether the resulting `CryptoKey` objects may be exported.\n * Set `false` on backends that store `CryptoKey` references directly (e.g.\n * IndexedDB). Set `true` when the private key must round-trip through JWK or\n * PKCS#8 (e.g. encrypted-file backends).\n * @returns Success with the generated `CryptoKeyPair`, or Failure with error context.\n */\n generateKeyPair(algorithm: KeyPairAlgorithm, extractable: boolean): Promise<Result<CryptoKeyPair>>;\n\n /**\n * Exports the public half of a keypair as a JSON Web Key.\n * @param publicKey - The public `CryptoKey` to export. Must be an `extractable`\n * key generated for an asymmetric algorithm.\n * @returns Success with the JWK, or Failure with error context.\n */\n exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>>;\n\n /**\n * Re-imports a public-key JWK as a `CryptoKey` usable for verification or\n * encryption (depending on algorithm).\n * @param jwk - The JSON Web Key produced by {@link CryptoUtils.ICryptoProvider.exportPublicKeyJwk | exportPublicKeyJwk}.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} the\n * key was generated for. Determines the import parameters and key usages.\n * @returns Success with the imported public `CryptoKey`, or Failure with error context.\n */\n importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>>;\n\n /**\n * Wraps `plaintext` for delivery to the holder of the private key paired\n * with `recipientPublicKey`. Uses ECIES with ECDH P-256, HKDF-SHA256, and\n * AES-GCM-256.\n *\n * Generates a fresh ephemeral keypair per call; the ephemeral private key\n * is discarded after the shared-secret derive. Only the recipient (with the\n * matching private key) and the same HKDF parameters can recover\n * `plaintext`.\n *\n * Empty `plaintext` is permitted; the resulting wrap contains only the\n * 16-byte GCM authentication tag and round-trips back to an empty\n * `Uint8Array`.\n * @param plaintext - The bytes to wrap. Any length supported by AES-GCM\n * (in practice, well below 2^39 - 256 bits).\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * Must have algorithm name `'ECDH'` and named curve `'P-256'`; mismatched\n * algorithm or curve yields a `Failure` with error context.\n * @param options - HKDF parameters; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with error context.\n */\n wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>>;\n\n /**\n * Inverse of {@link CryptoUtils.ICryptoProvider.wrapBytes | wrapBytes}.\n * Recovers the original `plaintext` from a wrapped payload using the\n * recipient's private key.\n *\n * Returns a `Failure` (never throws) on any of:\n * - Tampered nonce or ciphertext (AES-GCM authentication fails)\n * - Wrong private key (different shared secret derives a different wrap key)\n * - Wrong HKDF parameters (different wrap key)\n * - Malformed `ephemeralPublicKey` JWK\n * - Malformed base64 in `nonce` or `ciphertext`\n * @param wrapped - The wrapped payload produced by `wrapBytes`.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private\n * `CryptoKey`. Must have algorithm name `'ECDH'` and named curve `'P-256'`,\n * and key usages including `'deriveKey'` or `'deriveBits'`.\n * @param options - The same HKDF parameters used at wrap time.\n * @returns `Success` with the original `plaintext`, or `Failure` with error context.\n */\n unwrapBytes(\n wrapped: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>>;\n}\n\n// ============================================================================\n// Encryption Provider Interface\n// ============================================================================\n\n/**\n * High-level interface for encrypting JSON content by secret name.\n *\n * This abstraction unifies two common encryption workflows:\n * - **KeyStore**: looks up the named secret and crypto provider from the vault\n * - **DirectEncryptionProvider**: uses a pre-supplied key and crypto provider,\n * optionally bound to a specific secret name for safety\n *\n * Callers that need to encrypt (e.g. `EditableCollection.save()`) depend on\n * this interface rather than on `KeyStore` directly, allowing mix-and-match.\n *\n * @public\n */\nexport interface IEncryptionProvider {\n /**\n * Encrypts JSON content under a named secret.\n *\n * @param secretName - Name of the secret to encrypt with\n * @param content - JSON-safe content to encrypt\n * @param metadata - Optional unencrypted metadata to include in the encrypted file\n * @returns Success with encrypted file structure, or Failure with error context\n */\n encryptByName<TMetadata = JsonValue>(\n secretName: string,\n content: JsonValue,\n metadata?: TMetadata\n ): Promise<Result<IEncryptedFile<TMetadata>>>;\n}\n\n// ============================================================================\n// Encryption Configuration\n// ============================================================================\n\n/**\n * Behavior when an encrypted file cannot be decrypted.\n * @public\n */\nexport type EncryptedFileErrorMode =\n | 'fail' // Return failure, abort loading\n | 'skip' // Skip file silently, continue loading others\n | 'warn'; // Log warning, skip file, continue loading\n\n/**\n * Function type for dynamic secret retrieval.\n * @public\n */\nexport type SecretProvider = (secretName: string) => Promise<Result<Uint8Array>>;\n\n/**\n * Configuration for encrypted file handling during loading.\n * @public\n */\nexport interface IEncryptionConfig {\n /**\n * Named secrets available for decryption.\n */\n readonly secrets?: ReadonlyArray<INamedSecret>;\n\n /**\n * Alternative: dynamic secret provider function.\n * Called when a secret is not found in the secrets array.\n */\n readonly secretProvider?: SecretProvider;\n\n /**\n * Crypto provider implementation (Node.js or browser).\n */\n readonly cryptoProvider: ICryptoProvider;\n\n /**\n * Behavior when decryption key is missing (default: 'fail').\n */\n readonly onMissingKey?: EncryptedFileErrorMode;\n\n /**\n * Behavior when decryption fails (default: 'fail').\n */\n readonly onDecryptionError?: EncryptedFileErrorMode;\n}\n\n// ============================================================================\n// Detection Helper\n// ============================================================================\n\n/**\n * Checks if a JSON object appears to be an encrypted file.\n * Uses the format field as a discriminator.\n * @param json - JSON object to check\n * @returns true if the object has the encrypted file format field\n * @public\n */\nexport function isEncryptedFile(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) {\n return false;\n }\n const obj = json as Record<string, unknown>;\n return obj.format === Constants.ENCRYPTED_FILE_FORMAT;\n}\n"]}
@@ -18,8 +18,9 @@
18
18
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
19
  // SOFTWARE.
20
20
  import * as crypto from 'crypto';
21
- import { captureResult, fail, Failure, succeed, Success } from '@fgv/ts-utils';
21
+ import { captureAsyncResult, captureResult, fail, Failure, succeed, Success } from '@fgv/ts-utils';
22
22
  import * as Constants from './constants';
23
+ import { keyPairAlgorithmParams } from './keyPairAlgorithmParams';
23
24
  /**
24
25
  * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.
25
26
  * Uses AES-256-GCM for authenticated encryption.
@@ -116,6 +117,18 @@ export class NodeCryptoProvider {
116
117
  });
117
118
  });
118
119
  }
120
+ /**
121
+ * Computes a SHA-256 hash of the given data.
122
+ * @param data - UTF-8 string to hash
123
+ * @returns `Success` with hex-encoded hash string, or `Failure` with an error.
124
+ */
125
+ async sha256(data) {
126
+ return captureResult(() => {
127
+ const hash = crypto.createHash('sha256');
128
+ hash.update(data, 'utf8');
129
+ return hash.digest('hex');
130
+ });
131
+ }
119
132
  // ============================================================================
120
133
  // Platform Utility Methods
121
134
  // ============================================================================
@@ -150,6 +163,144 @@ export class NodeCryptoProvider {
150
163
  }
151
164
  return Success.with(new Uint8Array(Buffer.from(base64, 'base64')));
152
165
  }
166
+ // ============================================================================
167
+ // Asymmetric Key Operations
168
+ // ============================================================================
169
+ /**
170
+ * Generates a new asymmetric keypair using Node's WebCrypto.
171
+ * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.
172
+ * @param extractable - Whether the resulting keys may be exported.
173
+ * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.
174
+ */
175
+ async generateKeyPair(algorithm, extractable) {
176
+ const params = keyPairAlgorithmParams[algorithm];
177
+ const result = await captureAsyncResult(() => crypto.webcrypto.subtle.generateKey(params.generateKey, extractable, params.keyPairUsages));
178
+ return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);
179
+ }
180
+ /**
181
+ * Exports a public `CryptoKey` as a JSON Web Key.
182
+ * @remarks
183
+ * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`
184
+ * does not enforce public-vs-private; without this guard a caller that
185
+ * passed an extractable private key would receive its private fields
186
+ * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.
187
+ * @param publicKey - Extractable public key to export.
188
+ * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.
189
+ */
190
+ async exportPublicKeyJwk(publicKey) {
191
+ if (publicKey.type !== 'public') {
192
+ return fail(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);
193
+ }
194
+ const result = await captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('jwk', publicKey));
195
+ return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);
196
+ }
197
+ /**
198
+ * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.
199
+ * @param jwk - The JSON Web Key produced by a prior export.
200
+ * @param algorithm - The algorithm the key was generated for.
201
+ * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.
202
+ */
203
+ async importPublicKeyJwk(jwk, algorithm) {
204
+ const params = keyPairAlgorithmParams[algorithm];
205
+ const result = await captureAsyncResult(() => crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages));
206
+ return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);
207
+ }
208
+ /**
209
+ * Wraps `plaintext` for the holder of `recipientPublicKey` using
210
+ * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See
211
+ * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.
212
+ * @param plaintext - The bytes to wrap.
213
+ * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.
214
+ * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.
215
+ * @returns `Success` with the wrapped payload, or `Failure` with an error.
216
+ */
217
+ async wrapBytes(plaintext, recipientPublicKey, options) {
218
+ const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');
219
+ if (recipientCheck.isFailure()) {
220
+ return fail(`wrapBytes failed: ${recipientCheck.message}`);
221
+ }
222
+ const subtle = crypto.webcrypto.subtle;
223
+ const result = await captureAsyncResult(async () => {
224
+ const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [
225
+ 'deriveKey'
226
+ ]));
227
+ const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: recipientPublicKey }, ephemeral.privateKey, { name: 'HKDF' }, false, ['deriveKey']);
228
+ const wrapKey = await subtle.deriveKey({ name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' }, hkdfBase, { name: 'AES-GCM', length: 256 }, false, ['encrypt']);
229
+ const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);
230
+ const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, plaintext);
231
+ const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);
232
+ return {
233
+ ephemeralPublicKey,
234
+ nonce: this.toBase64(nonce),
235
+ ciphertext: this.toBase64(new Uint8Array(ctBuf))
236
+ };
237
+ });
238
+ return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);
239
+ }
240
+ /**
241
+ * Unwraps a payload produced by `wrapBytes` using the recipient's private
242
+ * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.
243
+ * @param wrapped - The wrapped payload.
244
+ * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.
245
+ * @param options - HKDF salt and info matching the wrap call.
246
+ * @returns `Success` with the original `plaintext`, or `Failure` with an error.
247
+ */
248
+ async unwrapBytes(wrapped, recipientPrivateKey, options) {
249
+ const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');
250
+ if (recipientCheck.isFailure()) {
251
+ return fail(`unwrapBytes failed: ${recipientCheck.message}`);
252
+ }
253
+ const nonceResult = this.fromBase64(wrapped.nonce);
254
+ if (nonceResult.isFailure()) {
255
+ return fail(`unwrapBytes failed: nonce: ${nonceResult.message}`);
256
+ }
257
+ if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {
258
+ return fail(`unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`);
259
+ }
260
+ const ciphertextResult = this.fromBase64(wrapped.ciphertext);
261
+ if (ciphertextResult.isFailure()) {
262
+ return fail(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);
263
+ }
264
+ if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {
265
+ return fail(`unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`);
266
+ }
267
+ const subtle = crypto.webcrypto.subtle;
268
+ const result = await captureAsyncResult(async () => {
269
+ const ephemeralPub = await subtle.importKey('jwk', wrapped.ephemeralPublicKey, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
270
+ const hkdfBase = await subtle.deriveKey({ name: 'ECDH', public: ephemeralPub }, recipientPrivateKey, { name: 'HKDF' }, false, ['deriveKey']);
271
+ const wrapKey = await subtle.deriveKey({ name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' }, hkdfBase, { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
272
+ const ptBuf = await subtle.decrypt({ name: 'AES-GCM', iv: nonceResult.value }, wrapKey, ciphertextResult.value);
273
+ return new Uint8Array(ptBuf);
274
+ });
275
+ return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);
276
+ }
277
+ }
278
+ /**
279
+ * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`
280
+ * (public or private). Used by the wrap/unwrap methods to surface a clean
281
+ * `Failure` instead of letting the WebCrypto deriveKey call throw a less
282
+ * informative error later in the pipeline. Key usages are intentionally not
283
+ * checked here: WebCrypto already produces a specific error if `deriveKey` is
284
+ * not in `usages`, and `deriveBits` is an equally valid alternative usage that
285
+ * an explicit check would have to track.
286
+ * @param key - The CryptoKey to validate.
287
+ * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).
288
+ * @param label - Human-readable role label included in the failure message.
289
+ * @returns `Success` with the key (unchanged) when the algorithm, curve, and
290
+ * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.
291
+ */
292
+ function checkEcdhP256(key, keyType, label) {
293
+ if (key.algorithm.name !== 'ECDH') {
294
+ return fail(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);
295
+ }
296
+ const namedCurve = key.algorithm.namedCurve;
297
+ if (namedCurve !== 'P-256') {
298
+ return fail(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);
299
+ }
300
+ if (key.type !== keyType) {
301
+ return fail(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);
302
+ }
303
+ return succeed(key);
153
304
  }
154
305
  /**
155
306
  * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodeCryptoProvider.js","sourceRoot":"","sources":["../../../src/packlets/crypto-utils/nodeCryptoProvider.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ,OAAO,KAAK,MAAM,MAAM,QAAQ,CAAC;AACjC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAU,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC3G,OAAO,KAAK,SAAS,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AASlE;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAC7B;;;;;OAKG;IACI,KAAK,CAAC,OAAO,CAAC,SAAiB,EAAE,GAAe;QACrD,OAAO,aAAa,CAAC,GAAG,EAAE;YACxB,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,gBAAgB,EAAE,CAAC;gBAC9C,MAAM,IAAI,KAAK,CAAC,eAAe,SAAS,CAAC,gBAAgB,eAAe,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACxF,CAAC;YAED,qBAAqB;YACrB,MAAM,EAAE,GAAG,MAAM,CAAC,WAAW,CAAC,SAAS,CAAC,WAAW,CA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IAAI,CAAC,GAAG,KAAK,cAAc,OAAO,oBAAoB,GAAG,CAAC,IAAI,IAAI,CAAC,CAAC;IAC7E,CAAC;IACD,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAuB,IAAI,kBAAkB,EAAE,CAAC","sourcesContent":["// Copyright (c) 2024 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\nimport * as crypto from 'crypto';\nimport { captureAsyncResult, captureResult, fail, Failure, Result, succeed, Success } from '@fgv/ts-utils';\nimport * as Constants from './constants';\nimport { keyPairAlgorithmParams } from './keyPairAlgorithmParams';\nimport {\n ICryptoProvider,\n IEncryptionResult,\n IWrapBytesOptions,\n IWrappedBytes,\n KeyPairAlgorithm\n} from './model';\n\n/**\n * Node.js implementation of {@link CryptoUtils.ICryptoProvider} using the built-in crypto module.\n * Uses AES-256-GCM for authenticated encryption.\n * @public\n */\nexport class NodeCryptoProvider implements ICryptoProvider {\n /**\n * Encrypts plaintext using AES-256-GCM.\n * @param plaintext - UTF-8 string to encrypt\n * @param key - 32-byte encryption key\n * @returns `Success` with encryption result, or `Failure` with an error.\n */\n public async encrypt(plaintext: string, key: Uint8Array): Promise<Result<IEncryptionResult>> {\n return captureResult(() => {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n throw new Error(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n\n // Generate random IV\n const iv = crypto.randomBytes(Constants.GCM_IV_SIZE);\n\n // Create cipher\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n // Encrypt\n const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);\n\n // Get auth tag\n const authTag = cipher.getAuthTag();\n\n return {\n iv: new Uint8Array(iv),\n authTag: new Uint8Array(authTag),\n encryptedData: new Uint8Array(encrypted)\n };\n });\n }\n\n /**\n * Decrypts ciphertext using AES-256-GCM.\n * @param encryptedData - Encrypted bytes\n * @param key - 32-byte decryption key\n * @param iv - Initialization vector (12 bytes)\n * @param authTag - GCM authentication tag (16 bytes)\n * @returns `Success` with decrypted UTF-8 string, or `Failure` with an error.\n */\n public async decrypt(\n encryptedData: Uint8Array,\n key: Uint8Array,\n iv: Uint8Array,\n authTag: Uint8Array\n ): Promise<Result<string>> {\n if (key.length !== Constants.AES_256_KEY_SIZE) {\n return fail(`Key must be ${Constants.AES_256_KEY_SIZE} bytes, got ${key.length}`);\n }\n if (iv.length !== Constants.GCM_IV_SIZE) {\n return fail(`IV must be ${Constants.GCM_IV_SIZE} bytes, got ${iv.length}`);\n }\n if (authTag.length !== Constants.GCM_AUTH_TAG_SIZE) {\n return fail(`Auth tag must be ${Constants.GCM_AUTH_TAG_SIZE} bytes, got ${authTag.length}`);\n }\n\n return captureResult(() => {\n // Create decipher\n const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), Buffer.from(iv));\n\n // Set auth tag\n decipher.setAuthTag(Buffer.from(authTag));\n\n // Decrypt\n const decrypted = Buffer.concat([decipher.update(Buffer.from(encryptedData)), decipher.final()]);\n\n return decrypted.toString('utf8');\n }).withErrorFormat((e) => `Decryption failed: ${e}`);\n }\n\n /**\n * Generates a random 32-byte key suitable for AES-256.\n * @returns `Success` with generated key, or `Failure` with an error.\n */\n public async generateKey(): Promise<Result<Uint8Array>> {\n return captureResult(() => {\n const key = crypto.randomBytes(Constants.AES_256_KEY_SIZE);\n return new Uint8Array(key);\n });\n }\n\n /**\n * Derives a key from a password using PBKDF2.\n * @param password - Password string\n * @param salt - Salt bytes (should be at least 16 bytes)\n * @param iterations - Number of iterations (recommend 100000+)\n * @returns `Success` with derived 32-byte key, or `Failure` with an error.\n */\n public async deriveKey(\n password: string,\n salt: Uint8Array,\n iterations: number\n ): Promise<Result<Uint8Array>> {\n if (iterations < 1) {\n return fail('Iterations must be at least 1');\n }\n if (salt.length < 8) {\n return fail('Salt should be at least 8 bytes');\n }\n\n return new Promise((resolve) => {\n crypto.pbkdf2(\n password,\n Buffer.from(salt),\n iterations,\n Constants.AES_256_KEY_SIZE,\n 'sha256',\n (err, derivedKey) => {\n /* c8 ignore next 3 - PBKDF2 internal errors are hard to trigger with valid parameters */\n if (err) {\n resolve(fail(`Key derivation failed: ${err.message}`));\n } else {\n resolve(succeed(new Uint8Array(derivedKey)));\n }\n }\n );\n });\n }\n\n /**\n * Computes a SHA-256 hash of the given data.\n * @param data - UTF-8 string to hash\n * @returns `Success` with hex-encoded hash string, or `Failure` with an error.\n */\n public async sha256(data: string): Promise<Result<string>> {\n return captureResult(() => {\n const hash = crypto.createHash('sha256');\n hash.update(data, 'utf8');\n return hash.digest('hex');\n });\n }\n\n // ============================================================================\n // Platform Utility Methods\n // ============================================================================\n\n /**\n * Generates cryptographically secure random bytes.\n * @param length - Number of bytes to generate\n * @returns Success with random bytes, or Failure with error\n */\n public generateRandomBytes(length: number): Result<Uint8Array> {\n if (length < 1) {\n return Failure.with('Length must be at least 1');\n }\n return captureResult(() => new Uint8Array(crypto.randomBytes(length)));\n }\n\n /**\n * Encodes binary data to base64 string.\n * @param data - Binary data to encode\n * @returns Base64-encoded string\n */\n public toBase64(data: Uint8Array): string {\n return Buffer.from(data).toString('base64');\n }\n\n /**\n * Decodes base64 string to binary data.\n * @param base64 - Base64-encoded string\n * @returns Success with decoded bytes, or Failure if invalid base64\n */\n public fromBase64(base64: string): Result<Uint8Array> {\n // Check for obviously invalid characters\n if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64)) {\n return Failure.with('Invalid base64 string');\n }\n return Success.with(new Uint8Array(Buffer.from(base64, 'base64')));\n }\n\n // ============================================================================\n // Asymmetric Key Operations\n // ============================================================================\n\n /**\n * Generates a new asymmetric keypair using Node's WebCrypto.\n * @param algorithm - The {@link CryptoUtils.KeyPairAlgorithm | algorithm} to use.\n * @param extractable - Whether the resulting keys may be exported.\n * @returns `Success` with the generated `CryptoKeyPair`, or `Failure` with an error.\n */\n public async generateKeyPair(\n algorithm: KeyPairAlgorithm,\n extractable: boolean\n ): Promise<Result<CryptoKeyPair>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.subtle.generateKey(params.generateKey, extractable, params.keyPairUsages)\n );\n return result.withErrorFormat((e) => `Failed to generate ${algorithm} keypair: ${e}`);\n }\n\n /**\n * Exports a public `CryptoKey` as a JSON Web Key.\n * @remarks\n * Rejects non-public keys at runtime. WebCrypto's `exportKey('jwk', ...)`\n * does not enforce public-vs-private; without this guard a caller that\n * passed an extractable private key would receive its private fields\n * (`d`, `p`, `q`, ...) as JWK, defeating the method's name.\n * @param publicKey - Extractable public key to export.\n * @returns `Success` with the JWK, or `Failure` if not a public key or if export fails.\n */\n public async exportPublicKeyJwk(publicKey: CryptoKey): Promise<Result<JsonWebKey>> {\n if (publicKey.type !== 'public') {\n return fail(`exportPublicKeyJwk requires a public CryptoKey, got '${publicKey.type}'`);\n }\n const result = await captureAsyncResult(() => crypto.webcrypto.subtle.exportKey('jwk', publicKey));\n return result.withErrorFormat((e) => `Failed to export public key as JWK: ${e}`);\n }\n\n /**\n * Imports a public-key JWK as a `CryptoKey` for the requested algorithm.\n * @param jwk - The JSON Web Key produced by a prior export.\n * @param algorithm - The algorithm the key was generated for.\n * @returns `Success` with the imported public `CryptoKey`, or `Failure` with an error.\n */\n public async importPublicKeyJwk(jwk: JsonWebKey, algorithm: KeyPairAlgorithm): Promise<Result<CryptoKey>> {\n const params = keyPairAlgorithmParams[algorithm];\n const result = await captureAsyncResult(() =>\n crypto.webcrypto.subtle.importKey('jwk', jwk, params.importPublicKey, true, params.publicKeyUsages)\n );\n return result.withErrorFormat((e) => `Failed to import ${algorithm} public key from JWK: ${e}`);\n }\n\n /**\n * Wraps `plaintext` for the holder of `recipientPublicKey` using\n * ECIES (ECDH P-256 + HKDF-SHA256 + AES-GCM-256). See\n * {@link CryptoUtils.ICryptoProvider.wrapBytes | ICryptoProvider.wrapBytes}.\n * @param plaintext - The bytes to wrap.\n * @param recipientPublicKey - The recipient's ECDH P-256 public `CryptoKey`.\n * @param options - HKDF salt and info; see {@link CryptoUtils.IWrapBytesOptions | IWrapBytesOptions}.\n * @returns `Success` with the wrapped payload, or `Failure` with an error.\n */\n public async wrapBytes(\n plaintext: Uint8Array,\n recipientPublicKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<IWrappedBytes>> {\n const recipientCheck = checkEcdhP256(recipientPublicKey, 'public', 'recipient public key');\n if (recipientCheck.isFailure()) {\n return fail(`wrapBytes failed: ${recipientCheck.message}`);\n }\n const subtle = crypto.webcrypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeral = (await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, [\n 'deriveKey'\n ])) as CryptoKeyPair;\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: recipientPublicKey },\n ephemeral.privateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['encrypt']\n );\n const nonce = crypto.randomBytes(Constants.GCM_IV_SIZE);\n const ctBuf = await subtle.encrypt({ name: 'AES-GCM', iv: nonce }, wrapKey, plaintext);\n const ephemeralPublicKey = await subtle.exportKey('jwk', ephemeral.publicKey);\n return {\n ephemeralPublicKey,\n nonce: this.toBase64(nonce),\n ciphertext: this.toBase64(new Uint8Array(ctBuf))\n };\n });\n return result.withErrorFormat((e) => `wrapBytes failed: ${e}`);\n }\n\n /**\n * Unwraps a payload produced by `wrapBytes` using the recipient's private\n * key. See {@link CryptoUtils.ICryptoProvider.unwrapBytes | ICryptoProvider.unwrapBytes}.\n * @param wrapped - The wrapped payload.\n * @param recipientPrivateKey - The recipient's ECDH P-256 private `CryptoKey`.\n * @param options - HKDF salt and info matching the wrap call.\n * @returns `Success` with the original `plaintext`, or `Failure` with an error.\n */\n public async unwrapBytes(\n wrapped: IWrappedBytes,\n recipientPrivateKey: CryptoKey,\n options: IWrapBytesOptions\n ): Promise<Result<Uint8Array>> {\n const recipientCheck = checkEcdhP256(recipientPrivateKey, 'private', 'recipient private key');\n if (recipientCheck.isFailure()) {\n return fail(`unwrapBytes failed: ${recipientCheck.message}`);\n }\n const nonceResult = this.fromBase64(wrapped.nonce);\n if (nonceResult.isFailure()) {\n return fail(`unwrapBytes failed: nonce: ${nonceResult.message}`);\n }\n if (nonceResult.value.length !== Constants.GCM_IV_SIZE) {\n return fail(\n `unwrapBytes failed: nonce must be ${Constants.GCM_IV_SIZE} bytes (got ${nonceResult.value.length})`\n );\n }\n const ciphertextResult = this.fromBase64(wrapped.ciphertext);\n if (ciphertextResult.isFailure()) {\n return fail(`unwrapBytes failed: ciphertext: ${ciphertextResult.message}`);\n }\n if (ciphertextResult.value.length < Constants.GCM_AUTH_TAG_SIZE) {\n return fail(\n `unwrapBytes failed: ciphertext must be at least ${Constants.GCM_AUTH_TAG_SIZE} bytes (got ${ciphertextResult.value.length})`\n );\n }\n const subtle = crypto.webcrypto.subtle;\n const result = await captureAsyncResult(async () => {\n const ephemeralPub = await subtle.importKey(\n 'jwk',\n wrapped.ephemeralPublicKey,\n { name: 'ECDH', namedCurve: 'P-256' },\n false,\n []\n );\n const hkdfBase = await subtle.deriveKey(\n { name: 'ECDH', public: ephemeralPub },\n recipientPrivateKey,\n { name: 'HKDF' },\n false,\n ['deriveKey']\n );\n const wrapKey = await subtle.deriveKey(\n { name: 'HKDF', salt: options.salt, info: options.info, hash: 'SHA-256' },\n hkdfBase,\n { name: 'AES-GCM', length: 256 },\n false,\n ['decrypt']\n );\n const ptBuf = await subtle.decrypt(\n { name: 'AES-GCM', iv: nonceResult.value },\n wrapKey,\n ciphertextResult.value\n );\n return new Uint8Array(ptBuf);\n });\n return result.withErrorFormat((e) => `unwrapBytes failed: ${e}`);\n }\n}\n\n/**\n * Verifies that `key` is an ECDH P-256 `CryptoKey` of the expected `keyType`\n * (public or private). Used by the wrap/unwrap methods to surface a clean\n * `Failure` instead of letting the WebCrypto deriveKey call throw a less\n * informative error later in the pipeline. Key usages are intentionally not\n * checked here: WebCrypto already produces a specific error if `deriveKey` is\n * not in `usages`, and `deriveBits` is an equally valid alternative usage that\n * an explicit check would have to track.\n * @param key - The CryptoKey to validate.\n * @param keyType - The required `key.type` ('public' for wrap, 'private' for unwrap).\n * @param label - Human-readable role label included in the failure message.\n * @returns `Success` with the key (unchanged) when the algorithm, curve, and\n * type all match; otherwise `Failure` with `<label> must be ECDH P-256 (...)`.\n */\nfunction checkEcdhP256(key: CryptoKey, keyType: 'public' | 'private', label: string): Result<CryptoKey> {\n if (key.algorithm.name !== 'ECDH') {\n return fail(`${label} must be ECDH P-256 (got algorithm '${key.algorithm.name}')`);\n }\n const namedCurve = (key.algorithm as EcKeyAlgorithm).namedCurve;\n if (namedCurve !== 'P-256') {\n return fail(`${label} must be ECDH P-256 (got curve '${namedCurve}')`);\n }\n if (key.type !== keyType) {\n return fail(`${label} must be a ${keyType} CryptoKey (got '${key.type}')`);\n }\n return succeed(key);\n}\n\n/**\n * Singleton instance of {@link CryptoUtils.NodeCryptoProvider}.\n * @public\n */\nexport const nodeCryptoProvider: NodeCryptoProvider = new NodeCryptoProvider();\n"]}